dev-master
9999999-dev http://github.com/digitalcreations/jsonJSON Serializer
MIT
The Requires
- php >=5.6.0
- phpdocumentor/reflection-docblock 2.*
The Development Requires
json serializer
Wallogit.com
2017 © Pedro Peláez
JSON Serializer
, (*1)
Allow serializing directly to classes using only phpDoc and type hints., (*2)
$ composer install dc/json
Or add it to composer.json:, (*3)
"require": {
"dc/json": "0.*"
}
$ composer install
This package suggests dc/ioc and dc/cache, but it really is a very strong recommendation. It will be painful or slow to use without it., (*4)
Get hold of a new \DC\JSON\Serializer and start serializing:, (*6)
class Cat {
/** @var string */
public $name;
}
$json = '[{ "name": "Sniffles" }, { "name": "Snuggles" }]';
$serializer = new \DC\JSON\Serializer();
$cats = $serializer->deserialize($catsJson, '\Cat[]');
If you are using a dc/ioc container, you'll need to do this:, (*7)
\DC\JSON\IoC\SerializerSetup::setup($container);
You can register a serialization handler to change how a specific class is serialized. This is different from using the
JsonSerializable interface in PHP, as a serialization handler allows you to change how built-in classes are serialized
and deserialized., (*8)
The interface itself is easy to implement. The library comes with one default handler, which serializes \DateTime
objects to and from ISO-8601 format. Look at that handler for a good example., (*9)
If you want to register serialization your own handlers, it is easiest to do using IoC:, (*10)
$container->register('\MyHandler')->to('\DC\JSON\Handler')->withContainerLifetime();
Classes are constructed in this manner:, (*11)
setX for the remaining values (this is controlled by convention, which you can
override). Use them.So, given this class:, (*12)
class Cat {
private $name;
private $age;
public $paws = 4;
function __construct($name) {
$this->name = $name;
}
function setAge($age) {
$this->age = $age;
}
}
...and this JSON:, (*13)
{
"name": "Snuggles",
"age": 6,
"paws": 4
}
...These two are equivalent:, (*14)
$cat = $serializer->deserialize($json, '\Cat');
// or
$cat = new \Cat("Snuggles");
$cat->setAge(6);
$cat->paws = 4;
It is no secret that json_decode and json_encode is a lot faster than this package. In fact, we use those internally
for the actual serialization. The magic of this package gets applied before serialization and after deserialization., (*15)
Using a combination of type hints and documentation, we are smart about constructing your objects the way they were intended to be constructed. But, parsing your documentation is resource intensive, therefore it is good practice to heed a few rules:, (*16)
dc/cache and dc/cache-memcache, and provide it to the serializer. If you do, all the information obtained
from the reflection is cached for a while.When using a primed cache, deserializing is about 4-5 times as slow a json_decode., (*17)
JSON Serializer
MIT
json serializer