PHPackages                             nilportugues/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. [API Development](/categories/api)
4. /
5. nilportugues/serializer

ActiveLibrary[API Development](/categories/api)

nilportugues/serializer
=======================

Serialize PHP variables, including objects, in any format. Support to unserialize it too.

1.2.1(7y ago)51259.4k↑36%19[6 issues](https://github.com/nilportugues/serializer/issues)[1 PRs](https://github.com/nilportugues/serializer/pulls)6MITPHPPHP &gt;=5.6.0

Since Jul 18Pushed 4y ago4 watchersCompare

[ Source](https://github.com/nilportugues/serializer)[ Packagist](https://packagist.org/packages/nilportugues/serializer)[ Docs](http://nilportugues.com)[ RSS](/packages/nilportugues-serializer/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (5)Versions (18)Used By (6)

Serializer for PHP
==================

[](#serializer-for-php)

[![Build Status](https://camo.githubusercontent.com/62810f59b04853731cf4c2672c1dc4f6cd56b2fc26222a3cf154601c4a9384a6/68747470733a2f2f7472617669732d63692e6f72672f6e696c706f727475677565732f7068702d73657269616c697a65722e737667)](https://travis-ci.org/nilportugues/php-serializer)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/6f10efd0a5fc0c8bd800396e898ddd45c98ef2d37530bc9f0396138e2c6d9351/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6e696c706f727475677565732f73657269616c697a65722f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/nilportugues/serializer/?branch=master) [![SensioLabsInsight](https://camo.githubusercontent.com/436039aa6480e096a314a1853fcda557ee1c4615496a443c3c1504a53f29955d/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f37616530356262612d393835642d343335392d386130302d3332303966383566316437372f6d696e692e706e673f)](https://insight.sensiolabs.com/projects/7ae05bba-985d-4359-8a00-3209f85f1d77)[![Latest Stable Version](https://camo.githubusercontent.com/bd142ef08a3fa7efba9752737a7d5bdb32aea51c75546eb92b107cada9fdce4c/68747470733a2f2f706f7365722e707567782e6f72672f6e696c706f727475677565732f73657269616c697a65722f762f737461626c65)](https://packagist.org/packages/nilportugues/serializer)[![Total Downloads](https://camo.githubusercontent.com/22abb9327c784c361e01842293cda207cc7f1068ffaf3307489350fe8c306657/68747470733a2f2f706f7365722e707567782e6f72672f6e696c706f727475677565732f73657269616c697a65722f646f776e6c6f616473)](https://packagist.org/packages/nilportugues/serializer) [![License](https://camo.githubusercontent.com/244e241d5cd3efde2005bb5e97876bd26a43cb5557e6a48c954e4c7d82166545/68747470733a2f2f706f7365722e707567782e6f72672f6e696c706f727475677565732f73657269616c697a65722f6c6963656e7365)](https://packagist.org/packages/nilportugues/serializer)[![Donate](https://camo.githubusercontent.com/7b6de155df30b37b25eb5fec52f9213680c3dbf067dfb7d7e2850ac4096c7d05/68747470733a2f2f7777772e70617970616c6f626a656374732e636f6d2f656e5f55532f692f62746e2f62746e5f646f6e6174655f534d2e676966)](https://paypal.me/nilportugues)

- [Installation](#installation)
- [Introduction](#introduction)
- [Features](#features)
- [Serialization](#serialization)
    - [Serializers (JSON, XML, YAML)](#serializers-json-xml-yaml)
    - [Example](#example)
    - [Custom Serializers](#custom-serializers)
- [Data Transformation](#data-transformation)
    - [Array Transformer](#array-transformer)
    - [Flat Array Transformer](#flat-array-transformer)
    - [XML Transformer](#xml-transformer)
    - [YAML Transformer](#yaml-transformer)
    - [JSON Transformer](#json-transformer)
    - [JSend Transformer](#jsend-transformer)
    - [JSON API Transformer](#json-api-transformer)
    - [HAL+JSON Transformer](#haljson-transformer)
- [Quality](#quality)
- [Contribute](#contribute)
- [Author](#author)
- [License](#license)

Installation
------------

[](#installation)

Use [Composer](https://getcomposer.org) to install the package:

```
$ composer require nilportugues/serializer
```

Introduction
------------

[](#introduction)

**What is serialization?**

In the context of data storage, serialization is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer, or transmitted across a network connection link) and reconstructed later in the same or another computer environment.

**Why not `serialize()` and `unserialize()`?**

These native functions rely on having the serialized classes loaded and available at runtime and tie your unserialization process to a `PHP` platform.

If the serialized string contains a reference to a class that cannot be instantiated (e.g. class was renamed, moved namespace, removed or changed to abstract) PHP will immediately die with a fatal error.

Is this a problem? Yes it is. Serialized data is now **unusable**.

Features
--------

[](#features)

- Serialize to **JSON**, **XML** and **YAML** formats.
- Serializes **exact copies** of the object provided:
- **All object properties**, public, protected and private are serialized.
- All properties from the current object, and all the inherited properties are read and serialized.
- Handles internal class serialization for objects such as SplFixedArray or classes implementing Traversable.
- Basic **Data Transformers provided** to convert objects to different output formats.
- **Production-ready**.
- **Extensible:** easily write your out `Serializer` format or data `Transformers`.

Serialization
-------------

[](#serialization)

For the serializer to work, all you need to do is pass in a PHP Object to the serializer and a Strategy to implement its string representation.

### Serializers (JSON, XML, YAML)

[](#serializers-json-xml-yaml)

- [NilPortugues\\Serializer\\JsonSerializer](https://github.com/nilportugues/serializer/blob/master/src/JsonSerializer.php)
- [NilPortugues\\Serializer\\XmlSerializer](https://github.com/nilportugues/serializer/blob/master/src/XmlSerializer.php)
- [NilPortugues\\Serializer\\YamlSerializer](https://github.com/nilportugues/serializer/blob/master/src/YamlSerializer.php)

### Example

[](#example)

In the following example a `$post` object is serialized into JSON.

**Code**

```
use NilPortugues\Serializer\Serializer;
use NilPortugues\Serializer\Strategy\JsonStrategy;

//Example object
$post = new Post(
  new PostId(9),
  'Hello World',
  'Your first post',
  new User(
      new UserId(1),
      'Post Author'
  ),
  [
      new Comment(
          new CommentId(1000),
          'Have no fear, sers, your king is safe.',
          new User(new UserId(2), 'Barristan Selmy'),
          [
              'created_at' => (new DateTime('2015/07/18 12:13:00'))->format('c'),
              'accepted_at' => (new DateTime('2015/07/19 00:00:00'))->format('c'),
          ]
      ),
  ]
);

//Serialization
$serializer = new JsonSerializer();

$serializedObject = $serializer->serialize($post);

//Returns: true
var_dump($post == $serializer->unserialize($serializedObject));

echo $serializedObject;
```

The object, before it's transformed into an output format, is an array with all the necessary data to be rebuild using unserialize method.

**Output**

```
{
    "@type": "Acme\\\\Domain\\\\Dummy\\\\Post",
    "postId": {
        "@type": "Acme\\\\Domain\\\\Dummy\\\\ValueObject\\\\PostId",
        "postId": {
            "@scalar": "integer",
            "@value": 14
        }
    },
    "title": {
        "@scalar": "string",
        "@value": "Hello World"
    },
    "content": {
        "@scalar": "string",
        "@value": "Your first post"
    },
    "author": {
        "@type": "Acme\\\\Domain\\\\Dummy\\\\User",
        "userId": {
            "@type": "Acme\\\\Domain\\\\Dummy\\\\ValueObject\\\\UserId",
            "userId": {
                "@scalar": "integer",
                "@value": 1
            }
        },
        "name": {
            "@scalar": "string",
            "@value": "Post Author"
        }
    },
    "comments": {
        "@map": "array",
        "@value": [
            {
                "@type": "Acme\\\\Domain\\\\Dummy\\\\Comment",
                "commentId": {
                    "@type": "Acme\\\\Domain\\\\Dummy\\\\ValueObject\\\\CommentId",
                    "commentId": {
                        "@scalar": "integer",
                        "@value": 1000
                    }
                },
                "dates": {
                    "@map": "array",
                    "@value": {
                        "created_at": {
                            "@scalar": "string",
                            "@value": "2015-07-18T12:13:00+00:00"
                        },
                        "accepted_at": {
                            "@scalar": "string",
                            "@value": "2015-07-19T00:00:00+00:00"
                        }
                    }
                },
                "comment": {
                    "@scalar": "string",
                    "@value": "Have no fear, sers, your king is safe."
                },
                "user": {
                    "@type": "Acme\\\\Domain\\\\Dummy\\\\User",
                    "userId": {
                        "@type": "Acme\\\\Domain\\\\Dummy\\\\ValueObject\\\\UserId",
                        "userId": {
                            "@scalar": "integer",
                            "@value": 2
                        }
                    },
                    "name": {
                        "@scalar": "string",
                        "@value": "Barristan Selmy"
                    }
                }
            }
        ]
    }
}'
```

### Custom Serializers

[](#custom-serializers)

If a custom serialization strategy is preferred, the `Serializer` class should be used instead. A `CustomStrategy` must implement the `StrategyInterface`.

Usage is as follows:

```
use NilPortugues\Serializer\Serializer;
use NilPortugues\Serializer\Strategy\CustomStrategy;

$serializer = new Serializer(new CustomStrategy());

echo $serializer->serialize($post);
```

---

Data Transformation
-------------------

[](#data-transformation)

Transformer classes **greatly differ** from a `Strategy` class because these cannot `unserialize()` as all class references are lost in the process of transformation.

To obtain transformations instead of the `Serializer` class usage of `DeepCopySerializer` is required.

The Serializer library comes with a set of defined Transformers that implement the `StrategyInterface`. Usage is as simple as before, pass a Transformer as a `$strategy`.

**For instance:**

```
//...same as before ...

$serializer = new DeepCopySerializer(new JsonTransformer());
echo $serializer->serialize($post);
```

Following, there are some examples and its output, given the `$post` object as data to be Transformed.

### Array Transformer

[](#array-transformer)

- [`NilPortugues\Serializer\Transformer\ArrayTransformer`](https://github.com/nilportugues/serializer/blob/master/src/Transformer/ArrayTransformer.php)

```
array(
  'postId' => 9,
  'title' => 'Hello World',
  'content' => 'Your first post',
  'author' => array(
       'userId' => 1,
       'name' => 'Post Author',
   ),
  'comments' => array(
          0 => array(
           'commentId' => 1000,
           'dates' => array(
              'created_at' => '2015-07-18T12:13:00+02:00',
              'accepted_at' => '2015-07-19T00:00:00+02:00',
            ),
           'comment' => 'Have no fear, sers, your king is safe.',
           'user' => array(
             'userId' => 2,
             'name' => 'Barristan Selmy',
            ),
          ),
      ),
);
```

### Flat Array Transformer

[](#flat-array-transformer)

- [`NilPortugues\Serializer\Transformer\FlatArrayTransformer`](https://github.com/nilportugues/serializer/blob/master/src/Transformer/FlatArrayTransformer.php)

```
array(
  'postId' => 9,
  'title' => 'Hello World',
  'content' => 'Your first post',
  'author.userId' => 1,
  'author.name' => 'Post Author',
  'comments.0.commentId' => 1000,
  'comments.0.dates.created_at' => '2015-07-18T12:13:00+02:00',
  'comments.0.dates.accepted_at' => '2015-07-19T00:00:00+02:00',
  'comments.0.comment' => 'Have no fear, sers, your king is safe.',
  'comments.0.user.userId' => 2,
  'comments.0.user.name' => 'Barristan Selmy',
);
```

### XML Transformer

[](#xml-transformer)

- [`NilPortugues\Serializer\Transformer\XmlTransformer`](https://github.com/nilportugues/serializer/blob/master/src/Transformer/XmlTransformer.php)

```

  9
  Hello World
  Your first post

    1
    Post Author

      1000

        2015-07-18T12:13:00+02:00
        2015-07-19T00:00:00+02:00

      Have no fear, sers, your king is safe.

        2
        Barristan Selmy

```

### YAML Transformer

[](#yaml-transformer)

- [`NilPortugues\Serializer\Transformer\YamlTransformer`](https://github.com/nilportugues/serializer/blob/master/src/Transformer/YamlTransformer.php)

```
title: 'Hello World'
content: 'Your first post'
author:
    userId: 1
    name: 'Post Author'
comments:
    - { commentId: 1000, dates: { created_at: '2015-07-18T12:13:00+02:00', accepted_at: '2015-07-19T00:00:00+02:00' }, comment: 'Have no fear, sers, your king is safe.', user: { userId: 2, name: 'Barristan Selmy' } }
```

### Json Transformer

[](#json-transformer)

JsonTransformer comes in 2 flavours. For object to JSON transformation the following transformer should be used:

- [`NilPortugues\Serializer\Transformer\JsonTransformer`](https://github.com/nilportugues/serializer/blob/master/src/Transformer/JsonTransformer.php)

**Output**

```
{
    "postId": 9,
    "title": "Hello World",
    "content": "Your first post",
    "author": {
        "userId": 1,
        "name": "Post Author"
    },
    "comments": [
        {
            "commentId": 1000,
            "dates": {
                "created_at": "2015-07-18T13:34:55+02:00",
                "accepted_at": "2015-07-18T14:09:55+02:00"
            },
            "comment": "Have no fear, sers, your king is safe.",
            "user": {
                "userId": 2,
                "name": "Barristan Selmy"
            }
        }
    ]
}
```

If your desired output is for **API consumption**, you may like to check out the JsonTransformer library, or require it using:

```
$ composer require nilportugues/json
```

### JSend Transformer

[](#jsend-transformer)

JSend Transformer has been built to transform data into valid **JSend** specification resources.

Please check out the [JSend Transformer](https://github.com/nilportugues/jsend-transformer) or download it using:

```
$ composer require nilportugues/jsend
```

### JSON API Transformer

[](#json-api-transformer)

JSON API Transformer has been built to transform data into valid **JSON API** specification resources.

Please check out the [JSON API Transformer](https://github.com/nilportugues/jsonapi-transformer) or download it using:

```
$ composer require nilportugues/json-api
```

### HAL+JSON Transformer

[](#haljson-transformer)

HAL+JSON Transformer has been built for **HAL+JSON API creation**. Given an object and a series of mappings a valid HAL+JSON resource representation is given as output.

Please check out the [HAL+JSON API Transformer](https://github.com/nilportugues/hal-json-transformer) or download it using:

```
$ composer require nilportugues/haljson
```

---

Quality
-------

[](#quality)

To run the PHPUnit tests at the command line, go to the tests directory and issue `phpunit`.

This library attempts to comply with [PSR-2](http://www.php-fig.org/psr/psr-2/) and [PSR-4](http://www.php-fig.org/psr/psr-4/).

If you notice compliance oversights, please send a patch via pull request.

Contribute
----------

[](#contribute)

Contributions to the package are always welcome!

- Report any bugs or issues you find on the [issue tracker](https://github.com/nilportugues/serializer/issues/new).
- You can grab the source code at the package's [Git repository](https://github.com/nilportugues/serializer).

Authors
-------

[](#authors)

- [Nil Portugués Calderó](http://nilportugues.com)
- [The Community Contributors](https://github.com/nilportugues/serializer/graphs/contributors)

License
-------

[](#license)

The code base is licensed under the MIT license.

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance18

Infrequent updates — may be unmaintained

Popularity46

Moderate usage in the ecosystem

Community20

Small or concentrated contributor base

Maturity67

Established project with proven stability

 Bus Factor1

Top contributor holds 100% 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 ~68 days

Recently: every ~226 days

Total

17

Last Release

2860d ago

Major Versions

0.0.1 → 1.0.0-alpha2015-08-14

PHP version history (2 changes)0.0.1PHP &gt;=5.5.0

1.1.7PHP &gt;=5.6.0

### Community

Maintainers

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

---

Top Contributors

[![nilportugues](https://avatars.githubusercontent.com/u/550948?v=4)](https://github.com/nilportugues "nilportugues (108 commits)")

---

Tags

apiarray-transformerdata-transformationhalhal-apijsend-transformerjsonjson-apijson-transformationjsonapimarshallerphpphp7serializationtransformerxmlxml-transformationyamlyaml-transformerymljsonserializeserializer

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[nathanmac/parser

Simple PHP Parser Utility Library for API Development

2151.0M3](/packages/nathanmac-parser)[nilportugues/laravel5-json-api

Laravel 5 JSON API Transformer Package

31232.4k1](/packages/nilportugues-laravel5-json-api)[zumba/json-serializer

Serialize PHP variables, including objects, in JSON format. Support to unserialize it too.

129743.7k13](/packages/zumba-json-serializer)[nilportugues/jsonapi-bundle

Symfony 2 &amp; 3 JSON API Transformer Package

11446.0k](/packages/nilportugues-jsonapi-bundle)[nilportugues/json-api

Serializer transformers outputting valid API responses in JSON, JSON API and HAL+JSON API formats.

70106.2k3](/packages/nilportugues-json-api)[wayofdev/laravel-symfony-serializer

📦 Laravel wrapper around Symfony Serializer.

2113.6k](/packages/wayofdev-laravel-symfony-serializer)

PHPackages © 2026

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