PHP code example of thunderer / serializard

1. Go to this page and download the library: Download thunderer/serializard 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/ */

    

thunderer / serializard example snippets


final class User
{
    private $id;
    private $name;

    public function __construct(int $id, string $name) { /* ... */ }

    public function getId() { return $this->id; }
    public function getName() { return $this->name; }
}

$user = new User(1, 'Thomas');

$formats = new FormatContainer();
$formats->add('json', new JsonFormat());

$hydrators = new FallbackHydratorContainer();
$normalizers = new FallbackNormalizerContainer();
$serializard = new Serializard($formats, $normalizers, $hydrators);

$normalizers->add(User::class, function(User $user) {
    return [
        'id' => $user->getId(),
        'name' => $user->getName(),
    ];
});

$result = $serializard->serialize($user, 'json');
// result is {"id":1,"name":"Thomas"}

$hydrators->add(User::class, function(array $data) {
    return new User($data['id'], $data['name']);
});

$json = '{"id":1,"name":"Thomas"}';
$user = $serializard->unserialize($json, User::class, 'json');