PHP code example of nilportugues / serializer

1. Go to this page and download the library: Download nilportugues/serializer library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

nilportugues / serializer example snippets


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;

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

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

echo $serializer->serialize($post);

//...same as before ...

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

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',
            ),
          ),
      ),
);

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',
);