Serializer
, (*1)
This library allows you to serialize PHP structures of any complexity into PHP primitives: scalars, arrays, arrays of scalars, arrays of arrays, etc. The result can be then safely stored somewhere or passed anywhere using serialize()
, json_encode()
or any other way to convert plain arrays into string., (*2)
This library contains built-in serializers for:, (*3)
null
- scalars (bool, int, float, string)
- PHP
resource
type
- arrays and
\Traversable
\DateTime
- objects (which are flexibly configurable via custom configurations)
Installation
This library is managed via composer. You can install it by calling:, (*4)
$ composer require botanick/serializer
or manually adding it to your composer.json
:, (*5)
"require": {
"botanick/serializer": "dev-master"
}
Usage
Serializer usage is split into two general steps., (*6)
First of all, you should construct data serializers you are going to use. For example, if you are going to serialize only arrays of DateTimes, then your code will look like:, (*7)
use Botanick\Serializer\Serializer;
$arraySerializer = new Serializer\DataSerializer\ArraySerializer();
$dateTimeSerializer = new Serializer\DataSerializer\DateTimeSerializer();
// for detailed info on DateTimeSerializer options see an according section
$dateTimeSerializer->setDefaultOptions(array('format' => 'Y-m-d H:i:s'));
Then you need serializer to know about data serializers it should use:, (*8)
use Botanick\Serializer\Serializer;
$serializer = new Serializer\Serializer();
$serializer->addDataSerializer($arraySerializer, -9999);
$serializer->addDataSerializer($dateTimeSerializer, -8888);
That's all! Now you are able to serialize your data:, (*9)
$data = array(
new \DateTime(),
'yesterday' => new \DateTime('1 day ago'),
'dates' => array(
'some-date' => \DateTime::createFromFormat('H:i:s d.m.Y', '11:22:33 01.02.2003'),
'another-date' => \DateTime::createFromFormat('d.m.Y', '01.02.2003')
)
);
$serializedData = $serializer->serialize($data);
var_export($serializedData);
// you will see something like this:
// array (
// 0 => '2015-12-08 16:42:54',
// 'yesterday' => '2015-12-07 16:42:54',
// 'dates' =>
// array (
// 'some-date' => '2003-02-01 11:22:33',
// 'another-date' => '2003-02-01 16:42:54',
// ),
// )
Documentation
- Data serializers:
- Config loaders (used in
ObjectSerializer
):
- Serializer itself: