PHPackages                             jurjean/spray-serializer - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. jurjean/spray-serializer

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

jurjean/spray-serializer
========================

2.0.0(10y ago)27.5k62PHPPHP &gt;=5.5.0

Since Jan 27Pushed 9y ago1 watchersCompare

[ Source](https://github.com/JurJean/SpraySerializer)[ Packagist](https://packagist.org/packages/jurjean/spray-serializer)[ RSS](/packages/jurjean-spray-serializer/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (6)Versions (17)Used By (2)

SpraySerializer
===============

[](#sprayserializer)

Fast and easy serialization and deserialization of php objects.

[![Build Status](https://camo.githubusercontent.com/98038e036f46eff46fd836d9ad278ce01dd63d40364e41114442c8339c842585/68747470733a2f2f7365637572652e7472617669732d63692e6f72672f4a75724a65616e2f537072617953657269616c697a65722e706e673f6272616e63683d6d6173746572)](http://travis-ci.org/JurJean/SpraySerializer)

Internals
---------

[](#internals)

Serialization is performed by attaching to a specific class scope using the Closure::bind method. To keep things fast, reflection is only used while generating the serialization code.

How to use
----------

[](#how-to-use)

Let's start with a class to serialize. Note that the annotations hint the serializer, and that they're required for deserializing objects.

```
/**
 * Person
 */
class Person
{
    /**
     * @var string
     */
    private $name;

    /**
     * @var Address
     */
    private $address;

    public function __construct($name, Address $address)
    {
        $this->name = (string) $name;
        $this->address = $address;
    }
}

/**
 * Address
 */
class Address
{
    /**
     * @var string
     */
    private $street;

    public function __construct($street)
    {
        $this->street = (string) $street;
    }
}
```

Then we'll initialize the serializer.

```
$serializer = new Serializer();
$serializer->attach(
    new ObjectListener(
        new SerializerLocator(
            new SerializerRegistry(),
            new ObjectSerializerGenerator(
                new AnnotationBackedPropertyInfo()
            ),
            new ArrayCache('Serializer')
        )
    )
);
```

Now we can serialize almost any object to an array and back to an object.

```
$data = $serializer->serialize(new Person('Name', new Address('Street')));
var_dump($data);
// array(2) {
//   'name' =>
//   string(4) "Name"
//   'address' =>
//   array(1) {
//     'street' =>
//     string(6) "Street"
//   }
// }

$object = $serializer->deserialize('Person', $data);
var_dump($object);
// class Person#8 (2) {
//   private $name =>
//   string(4) "Name"
//   private $address =>
//   class Address#18 (1) {
//     private $street =>
//     string(6) "Street"
//   }
// }
```

[Supported annotations](examples/simple.php)
--------------------------------------------

[](#supported-annotations)

As the example above shows, the serializer uses default docblock annotations to determine the serialization strategy. The following annotations are supported:

```
class SerializeMe
{
    /**
     * @var string
     */
    private $string;

    /**
     * @var int
     */
    private $int;

    /**
     * @var integer
     */
    private $integer;

    /**
     * @var bool
     */
    private $bool;

    /**
     * @var boolean
     */
    private $boolean;

    /**
     * @var float
     */
    private $float;

    /**
     * @var double
     */
    private $double;

    /**
     * @var array
     */
    private $array;

    /**
     * @var Object
     */
    private $object;

    /**
     * @var string[]
     */
    private $stringArray;

    /**
     * @var Object[]
     */
    private $objectArray;

    /**
     * @var array
     */
    private $stringArrayJavaStyle;

    /**
     * @var array
     */
    private $objectArrayJavaStyle;
}
```

[Almost any object](examples/custom.php)
----------------------------------------

[](#almost-any-object)

There're some limitations to the implemented serialization method. For instance, deserializing a DateTime(Immutable) object is not possible. For this reason, specialized serializers are added. You'll need to add these to the SerializerRegistry in your application bootstrap like so:

```
$registry = new SerializerRegistry();
$registry->add(new DateTimeSerializer());
$registry->add(new DateTimeImmutableSerializer());
$registry->add(new StdClassSerializer());

$serializer = new Serializer();
$serializer->attach(
    new ObjectListener(
        new SerializerLocator(
            $registry,
            new ObjectSerializerGenerator(
                new AnnotationBackedPropertyInfo()
            ),
            new ArrayCache('Serializer')
        )
    )
);
```

[Inheritance support](examples/inheritance.php)
-----------------------------------------------

[](#inheritance-support)

In order to support object inheritance (de)serialization, just the annotations is not enough. The *ObjectTypeListener* is required to enable this functionality:

```
$serializer = new Serializer();
$serializer->attach(
    new ObjectTypeListener()
);
$serializer->attach(
    new ObjectListener(
        new SerializerLocator(
            new SerializerRegistry(),
            new ObjectSerializerGenerator(
                new AnnotationBackedPropertyInfo()
            ),
            new ArrayCache('Serializer')
        )
    )
);
```

***Note:** Enabling this feature results in your data populated with `'__type' => 'ClassName'`.*

[Encryption support](examples/encryption.php)
---------------------------------------------

[](#encryption-support)

When your application requires encryption you'll have to attach the *EncryptionListener*:

```
$blockCipher = BlockCipher::factory('mcrypt', ['algo' => 'aes']);
$blockCipher->setKey('5eDCZRmyX8s7nbgV9f6pVrmRISdc5t8L');

$serializer = new Serializer();
$serializer->attach(
    new EncryptionListener(
        new EncryptorLocator(
            new EncryptorGenerator(new AnnotationBackedPropertyInfo()),
            new ArrayCache('Encryptor')
        ),
        $blockCipher
    )
);
$serializer->attach(
    new ObjectListener(
        new SerializerLocator(
            new SerializerRegistry(),
            new ObjectSerializerGenerator(
                new AnnotationBackedPropertyInfo()
            ),
            new ArrayCache('Serializer')
        )
    )
);
```

[Caching methods](examples/cache.php)
-------------------------------------

[](#caching-methods)

The library provides two methods of caching: array and file. The array cache is primarily useful for testing/development purposes. For production however, you're better off using the FileCache.

The file cache actually writes the generated serialization code to plain php files for later use (and therefore automatically cached in op-code cache).

Below is how you'd bootstrap the file cache for the serializer:

```
use Symfony\Component\Filesystem\Filesystem;

$serializer = new Serializer();
$serializer->attach(
    new ObjectListener(
        new SerializerLocator(
            new SerializerRegistry(),
            new ObjectSerializerGenerator(
                new AnnotationBackedPropertyInfo()
            ),
            new FileCache(new Filesystem(), '/path/to/cache/directory', 'Serializer')
        )
    )
);
```

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity24

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity66

Established project with proven stability

 Bus Factor1

Top contributor holds 97.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~70 days

Recently: every ~103 days

Total

7

Last Release

3677d ago

Major Versions

1.1.0 → 2.0.02016-04-14

PHP version history (2 changes)1.0.0PHP &gt;=5.4.0

1.1.0PHP &gt;=5.5.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/ba522e901313f2437eb205ef9863f5b7e54cb97c847d8fe8ca7f3d05b75a116d?d=identicon)[JurJean](/maintainers/JurJean)

---

Top Contributors

[![JurJean](https://avatars.githubusercontent.com/u/409761?v=4)](https://github.com/JurJean "JurJean (40 commits)")[![marek-binkowski-sim](https://avatars.githubusercontent.com/u/7207952?v=4)](https://github.com/marek-binkowski-sim "marek-binkowski-sim (1 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/jurjean-spray-serializer/health.svg)

```
[![Health](https://phpackages.com/badges/jurjean-spray-serializer/health.svg)](https://phpackages.com/packages/jurjean-spray-serializer)
```

###  Alternatives

[doctrine/rst-parser

PHP library to parse reStructuredText documents and generate HTML or LaTeX documents.

64233.6k9](/packages/doctrine-rst-parser)[couscous/couscous

Documentation website generator

84167.6k24](/packages/couscous-couscous)[liip/serializer

High performance serializer that works with code generated helpers to achieve high throughput.

128365.2k4](/packages/liip-serializer)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

595.2M386](/packages/shopware-core)[symfony/json-streamer

Provides powerful methods to read/write data structures from/into JSON streams.

14440.0k8](/packages/symfony-json-streamer)[shyim/danger-php

Port of danger to PHP

8544.9k](/packages/shyim-danger-php)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
