Flexible serializer encouraging good object design

Last update: Jan 15, 2021

Serializard

Build Status Latest Stable Version License Scrutinizer Code Quality Code Coverage Dependency Status

Serializard is a library for (un)serialization of data of any complexity. Its main focus is to give user as much flexibility as possible by delegating the (un)serialization logic to the programmer to encourage good object design and only supervising the process hiding the unpleasant details about it.

Installation

This library is available on Composer/Packagist as thunderer/serializard.

Usage

Let's consider a simple User class with two properties and some setup code:

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

Serialization

Serialization is controlled by registering handlers used in normalization phase:

$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"}

Unserialization

Unserialization can be controlled by registering callables able to reconstruct objects from data parsed from input text:

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

Formats

  • JSON in JsonFormat converts objects to JSON,
  • Array in ArrayFormat just returns object graph normalized to arrays of scalars,
  • YAML in YamlFormat converts objects to YAML (uses symfony/yaml),
  • XML in XmlFormat converts objects to XML (uses ext-dom).

License

See LICENSE file in the main directory of this library.

GitHub

https://github.com/thunderer/Serializard
You might also like...

Pretty Good Privacy (PGP) is an encryption program that provides cryptographic privacy and authentication for data communication.

Pretty Good Privacy (PGP) is an encryption program that provides cryptographic privacy and authentication for data communication. PGP is used for signing, encrypting, and decrypting texts, e-mails, files, directories, and whole disk partitions and to increase the security of e-mail communications. Phil Zimmermann developed PGP in 1991.

Dec 31, 2021

A Laravel 4 CMS – WARNING: This project is no longer being developed because there are many good alternatives now.

This is the main larapress repository. Warning: This Application is under development and not yet production ready! Important Links Installation Contr

Jan 23, 2022

A good, non-specialized Laravel base site for faster app development

Larastrap This is a non-specialized Laravel base site containing generalized components for faster development of nearly any type of site. It includes

Dec 11, 2016

churn-php is a package that helps you identify php files in your project that could be good candidates for refactoring

churn-php is a package that helps you identify php files in your project that could be good candidates for refactoring

churn-php Helps discover good candidates for refactoring. Table of Contents What Is it? Compatibility How to Install? How to Use? How to Configure? Si

May 23, 2022

Laravel Livewire component to show Events in a good looking monthly calendar

Laravel Livewire component to show Events in a good looking monthly calendar

Livewire Calendar This package allows you to build a Livewire monthly calendar grid to show events for each day. Events can be loaded from within the

May 25, 2022

A good plugin to play a sound when the player hits the enemy's head

HeadshotSound A good plugin to play a sound when the player hits the enemy's head. How to use Hit the player with a snowball, egg and bow in the head

May 6, 2022

A simple PHP library to transfer data from a source (object or array) to an object.

SimplexMapper A simple PHP library to transfer data from a source (object or array) to an object. $dbData = [ 'username' = 'pfazzi', 'emailAd

Jan 22, 2022

An article about alternative solution for convert object into a JSON Object for your api.

Do we really need a serializer for our JSON API? The last years I did build a lot of JSON APIs but personally was never happy about the magic of using

Feb 1, 2022

Your alter ego object. Takes the best of object and array worlds.

Supporting Opensource formapro\values is an MIT-licensed open source project with its ongoing development made possible entirely by the support of com

Jun 25, 2021

sample code for several design patterns in PHP 8

DesignPatternsPHP Read the Docs of DesignPatternsPHP or Download as PDF/Epub This is a collection of known design patterns and some sample codes on ho

May 18, 2022

A flexible, driver based Acl package for PHP 5.4+

A flexible, driver based Acl package for PHP 5.4+

Lock - Acl for PHP 5.4+ I'm sad to say that Lock is currently not maintained. I won't be able to offer support or accept new contributions for the cur

Mar 10, 2022

A powerful command line application framework for PHP. It's an extensible, flexible component, You can build your command-based application in seconds!

A powerful command line application framework for PHP. It's an extensible, flexible component, You can build your command-based application in seconds!

CLIFramework CLIFramework is a command-line application framework, for building flexiable, simple command-line applications. Commands and Subcommands

May 17, 2022

Output complex, flexible, AJAX/RESTful data structures.

Fractal Fractal provides a presentation and transformation layer for complex data output, the like found in RESTful APIs, and works really well with J

May 24, 2022

😎 Tracy: the addictive tool to ease debugging PHP code for cool developers. Friendly design, logging, profiler, advanced features like debugging AJAX calls or CLI support. You will love it.

😎 Tracy: the addictive tool to ease debugging PHP code for cool developers. Friendly design, logging, profiler, advanced features like debugging AJAX calls or CLI support. You will love it.

Tracy - PHP debugger Introduction Tracy library is a useful helper for everyday PHP programmers. It helps you to: quickly detect and correct errors lo

May 20, 2022

💎 Flexible, compiled and full-featured Dependency Injection Container with perfectly usable autowiring and support for all new PHP 7 features.

Nette Dependency Injection (DI) Introduction Purpose of the Dependecy Injection (DI) is to free classes from the responsibility for obtaining objects

May 26, 2022

FuelPHP v1.x is a simple, flexible, community driven PHP 5.3+ framework, based on the best ideas of other frameworks, with a fresh start! FuelPHP is fully PHP 7 compatible.

FuelPHP Version: 1.8.2 Website Release Documentation Release API browser Development branch Documentation Development branch API browser Support Forum

May 26, 2022

A flexible and feature-complete Redis client for PHP.

Predis A flexible and feature-complete Redis client for PHP 7.2 and newer. ATTENTION: you are on the README file of an unstable branch of Predis speci

May 18, 2022

Domain Driven Design PHP helper classes

carlosbuenosvinos/ddd This library will help you with typical DDD scenarios, for now: Application Services Interface Transactional Application Service

Apr 30, 2022

A fast & flexible router

Klein.php klein.php is a fast & flexible router for PHP 5.3+ Flexible regular expression routing (inspired by Sinatra) A set of boilerplate methods fo

May 19, 2022
Comments
  • 1. Default normalizer fallback

    • [x] added support for default normalizer fallback in FallbackNormalizerContainer,
    • [ ] improved README, TODO write docs for default normalizer function,
    • [x] converted array() syntax to PHP 5.4 [],
    • [x] introduced custom domain exceptions,
    • [x] added suggests block in composer.json with information for YAML and XML requirements,
    • [x] replaced string class names with PHP 5.5 ::class pseudoconstant,
    • [x] added Makefile with test target,
    • [x] added PHP 7.2 to Travis matrix, moved HHVM to allowed failures,
    • [x] many performance improvements (prefixed internal functions, logic optimizations),
    • [x] containers now throw exceptions themselves instead of returning nulls,
    • [x] introduced ClosureBindNormalizer which allows direct access to normalized class internals,
    • [x] ParentNormalizerContext uses clone instead of recreating the object each time.
    Reviewed by thunderer at 2018-02-16 22:00
  • 2. Remove root element alias from normalizers and hydrators containers

    • [x] normalizers container and hydrators container no longer require root element key,
    • [x] root element alias handling was moved to XmlFormat as it is the only one that required it,
    • [x] introduced RootElementProviderUtility to ease creation of these aliases,
    • [x] formally increased minimum PHP version to 5.5 in composer.json,
    • [x] updated README.
    Reviewed by thunderer at 2017-05-28 16:50
  • 3. Ideas

    Just a couple of ideas to remember:

    • [ ] introduce other formats - TOML, MsgPack, ProtoBuf,
    • [ ] DateTimeNormalizer using passed format,
    • [ ] do not check whether class or interface exists when registering a handler,
    • [ ] think about multiple handlers based on the object state - "normalizer resolvers",
    • [ ] hybrid normalizer + hydrator registration for single class, that can maybe share the context?
    • [ ] XmlFormat::parse() does not include element attributes,
    • [ ] XmlFormat is unable to serialize element attributes,
    • [ ] add Context to both directions,
    • [x] add normalization and hydration context with custom information (root object, parent object, maybe Request instance and so on),
    • [ ] add setDefault() to normalizer and hydrator containers,
    • [ ] allow more than one instance of object in cycle detection like Symfony Serializer does,
    • [x] PublicPropertiesNormalizer (done with GetObjectVarsNormalizer),
    • [ ] find a way to set max nesting limit - nesting resolver called instead of current one,
    • [x] split HandlerContainer into separate classes for normalizers and hydrators ~~and remove alias from method adding normalizers~~ (required in XML format),
    • [x] release first version,
    • [x] ~~add DoctrineProxyNormalizer~~ or fallback for class parents,
    • [x] SerializardFacade.
    Reviewed by thunderer at 2016-02-10 11:01
Output complex, flexible, AJAX/RESTful data structures.

Fractal Fractal provides a presentation and transformation layer for complex data output, the like found in RESTful APIs, and works really well with J

May 24, 2022
`LINQ to Object` inspired DSL for PHP

Ginq Array handling in PHP? Be happy with Ginq! Ginq is a DSL that can handle arrays and iterators of PHP unified. Ginq is inspired by Linq to Object,

Apr 17, 2022
Serializer component from Zend Framework

zend-serializer Repository abandoned 2019-12-31 This repository has moved to laminas/laminas-serializer. zend-serializer provides an adapter-based int

Jan 13, 2022
An HTML5 parser and serializer for PHP.

HTML5-PHP HTML5 is a standards-compliant HTML5 parser and writer written entirely in PHP. It is stable and used in many production websites, and has w

May 17, 2022
JSON:API serializer for PHP resources

kwai-jsonapi A JSON:API serializer for PHP classes using PHP attributes. Currently, this library has no support for links. Installation composer requi

Jan 19, 2022
Igbinary is a drop in replacement for the standard php serializer.

igbinary Igbinary is a drop in replacement for the standard php serializer. Instead of the time and space consuming textual representation used by PHP

Apr 29, 2022
[READ-ONLY] A flexible, lightweight and powerful Object-Relational Mapper for PHP, implemented using the DataMapper pattern. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp

CakePHP ORM The CakePHP ORM provides a powerful and flexible way to work with relational databases. Using a datamapper pattern the ORM allows you to m

Feb 24, 2022
the examples of head first object oriented analysis & design - in PHP

Head First object oriented analysis & design in (PHP) after cloning the repository, you have to install the project's dependancies by running the foll

Oct 16, 2021
Couscous is good.

layout home Couscous generates a GitHub pages website from your markdown documentation. Everything is documented on couscous.io. What follows is the d

May 15, 2022