2017 © Pedro Peláez
 

library serializer

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

image

nilportugues/serializer

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

  • Thursday, July 19, 2018
  • by nilportugues
  • Repository
  • 6 Watchers
  • 38 Stars
  • 76,749 Installations
  • PHP
  • 7 Dependents
  • 0 Suggesters
  • 15 Forks
  • 5 Open issues
  • 18 Versions
  • 9 % Grown

The README.md

Serializer for PHP

Build Status Scrutinizer Code Quality SensioLabsInsight Latest Stable Version Total Downloads License Donate, (*1)

Installation

Use Composer to install the package:, (*2)

$ composer require nilportugues/serializer

Introduction

What is serialization?, (*3)

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., (*4)

Why not serialize() and unserialize()?, (*5)

These native functions rely on having the serialized classes loaded and available at runtime and tie your unserialization process to a PHP platform., (*6)

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., (*7)

Is this a problem? Yes it is. Serialized data is now unusable., (*8)

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

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., (*9)

Serializers (JSON, XML, YAML)

Example

In the following example a $post object is serialized into JSON., (*10)

Code, (*11)

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., (*12)

Output, (*13)

{
    "@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

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

Usage is as follows:, (*15)

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

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

echo $serializer->serialize($post);

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., (*16)

To obtain transformations instead of the Serializer class usage of DeepCopySerializer is required., (*17)

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., (*18)

For instance:, (*19)

//...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., (*20)

Array Transformer

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

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 version="1.0" encoding="UTF-8"?>
<data>
  <postId type="integer">9</postId>
  <title type="string">Hello World</title>
  <content type="string">Your first post</content>
  <author>
    <userId type="integer">1</userId>
    <name type="string">Post Author</name>
  </author>
  <comments>
    <sequential-item>
      <commentId type="integer">1000</commentId>
      <dates>
        <created_at type="string">2015-07-18T12:13:00+02:00</created_at>
        <accepted_at type="string">2015-07-19T00:00:00+02:00</accepted_at>
      </dates>
      <comment type="string">Have no fear, sers, your king is safe.</comment>
      <user>
        <userId type="integer">2</userId>
        <name type="string">Barristan Selmy</name>
      </user>
    </sequential-item>
  </comments>
</data>

YAML Transformer

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

JsonTransformer comes in 2 flavours. For object to JSON transformation the following transformer should be used:, (*21)

Output, (*22)

{
    "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:, (*23)

$ composer require nilportugues/json

JSend Transformer

JSend Transformer has been built to transform data into valid JSend specification resources., (*24)

Please check out the JSend Transformer or download it using:, (*25)

$ composer require nilportugues/jsend

JSON API Transformer

JSON API Transformer has been built to transform data into valid JSON API specification resources., (*26)

Please check out the JSON API Transformer or download it using:, (*27)

$ composer require nilportugues/json-api

HAL+JSON 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., (*28)

Please check out the HAL+JSON API Transformer or download it using:, (*29)

$ composer require nilportugues/haljson

Quality

To run the PHPUnit tests at the command line, go to the tests directory and issue phpunit., (*30)

This library attempts to comply with PSR-2 and PSR-4., (*31)

If you notice compliance oversights, please send a patch via pull request., (*32)

Contribute

Contributions to the package are always welcome!, (*33)

Authors

License

The code base is licensed under the MIT license., (*34)

The Versions

19/07 2018

dev-master

9999999-dev http://nilportugues.com

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

  Sources   Download

MIT

The Requires

 

The Development Requires

json serializer serialize

19/07 2018

1.2.1

1.2.1.0 http://nilportugues.com

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

  Sources   Download

MIT

The Requires

 

The Development Requires

json serializer serialize

10/02 2017

1.2.0

1.2.0.0 http://nilportugues.com

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

  Sources   Download

MIT

The Requires

 

The Development Requires

json serializer serialize

11/06 2016
02/03 2016
25/01 2016
25/01 2016
21/11 2015
02/11 2015
29/08 2015

1.1.5

1.1.5.0 http://nilportugues.com

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

  Sources   Download

MIT

The Requires

  • php >=5.5.0

 

The Development Requires

json serializer serialize

28/08 2015

1.1.4

1.1.4.0 http://nilportugues.com

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

  Sources   Download

MIT

The Requires

  • php >=5.5.0

 

The Development Requires

json serializer serialize

27/08 2015

1.1.3

1.1.3.0 http://nilportugues.com

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

  Sources   Download

MIT

The Requires

  • php >=5.5.0

 

The Development Requires

json serializer serialize

25/08 2015

1.1.2

1.1.2.0 http://nilportugues.com

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

  Sources   Download

MIT

The Requires

  • php >=5.5.0

 

The Development Requires

json serializer serialize

23/08 2015

1.1.1

1.1.1.0 http://nilportugues.com

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

  Sources   Download

MIT

The Requires

  • php >=5.5.0

 

The Development Requires

json serializer serialize

16/08 2015

1.1.0

1.1.0.0 http://nilportugues.com

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

  Sources   Download

MIT

The Requires

  • php >=5.5.0

 

The Development Requires

json serializer serialize

15/08 2015

1.0.0

1.0.0.0 http://nilportugues.com

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

  Sources   Download

MIT

The Requires

  • php >=5.5.0

 

The Development Requires

json serializer serialize

14/08 2015

1.0.0-alpha

1.0.0.0-alpha http://nilportugues.com

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

  Sources   Download

MIT

The Requires

  • php >=5.5.0

 

The Development Requires

json serializer serialize

18/07 2015

0.0.1

0.0.1.0 http://nilportugues.com

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

  Sources   Download

GPL-3.0

The Requires

  • php >=5.5.0

 

The Development Requires

json serializer serialize