Flexible serializer encouraging good object design

Overview

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.

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.

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

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

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

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

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

[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

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

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

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

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

😎 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

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

Adjacency List’ed Closure Table database design pattern implementation for the Laravel framework.

ClosureTable This is a database manipulation package for the Laravel 5.4+ framework. You may want to use it when you need to store and operate hierarc

Someline Starter is a PHP framework for quick building Web Apps and Restful APIs, with modern PHP design pattern foundation.

Someline Starter PHP Framework Tested and used in production by Someline Inc. Someline Starter is a PHP framework for quick building Web Apps and Rest

Mind is the PHP code framework designed for developers. It offers a variety of solutions for creating design patterns, applications and code frameworks.
Mind is the PHP code framework designed for developers. It offers a variety of solutions for creating design patterns, applications and code frameworks.

Mind Mind is the PHP code framework designed for developers. It offers a variety of solutions for creating design patterns, applications and code fram

Simple WHOIS script with beautiful design.
Simple WHOIS script with beautiful design.

Simple PHP Whois It is ideal in terms of design and has easy operation. / Tasarım açısından idealdir ve kullanımı kolaydır. It has a simple interface.

Repo do vídeo do youtube de Design Patterns - Decorator
Repo do vídeo do youtube de Design Patterns - Decorator

DesignPatternsPHP-Decorator Repo do vídeo do Youtube de Design Patterns - Decorator Link do vídeo Decorator em PHP 8 Imagem de exemplo Link do cadastr

Need some filters? This package is based on the Repository Design Pattern to let you create specific queries easily.
Need some filters? This package is based on the Repository Design Pattern to let you create specific queries easily.

DevMakerLab/Laravel-Filters Need some filters? This package is based on the Repository Design Pattern to let you create specific queries easily. Insta

Comments
  • Default normalizer fallback

    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.
    opened by thunderer 0
  • Remove root element alias from normalizers and hydrators containers

    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.
    opened by thunderer 0
  • Ideas

    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.
    opened by thunderer 0
Releases(v0.4.0)
  • v0.4.0(Jan 15, 2021)

  • v0.3.1(May 28, 2017)

    Normalizers and hydrators containers no longer require root element key. Root element alias handling was moved to XmlFormat. Formally increased minimum PHP version to 5.5 in composer.json.

    Source code(tar.gz)
    Source code(zip)
  • v0.3.0(May 28, 2017)

    Added PHPUnit 6.x compatibility, added normalisation contexts to provide runtime process introspection (information about root and parent objects, tree level, and used format) with the ability to provide custom objects, added ReflectionHydrator, added CallbackNormalizer.

    Source code(tar.gz)
    Source code(zip)
  • v0.2.0(Mar 10, 2017)

    Hardened JSON format by checking json_last_error() before returning the result. Dropped support for PHP 5.3 and 5.4 because that function does not work properly (returns different values and reports no errors).

    Source code(tar.gz)
    Source code(zip)
  • v0.1.2(Aug 3, 2016)

  • v0.1.1(Jun 8, 2016)

  • v0.1.0(Feb 15, 2016)

Owner
Tomasz Kowalczyk
Working hard to bring back *engineering* in software engineering.
Tomasz Kowalczyk
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

The League of Extraordinary Packages 3.5k Jan 8, 2023
`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,

Atsushi Kanehara 191 Dec 19, 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

Zend Framework 45 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

null 1.2k Dec 31, 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

Franky Braem 1 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

Igbinary development 727 Dec 21, 2022
This component, based on the Symfony serializer and async-aws, is a human-readable and quick abstraction to easily store serialized objects in DynamoDB 🚀.

DynamoDB Storable This component, based on the Symfony serializer and async-aws, is a human-readable and quick abstraction to easily store serialized

Matthieu W. 2 Jun 19, 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

Muhammed ElFeqy 3 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

Couscous 828 Dec 15, 2022