Improved Serialization with JMS Serializer

The serialize/unserialize native PHP strategies have a problem when dealing with class and namespace refactoring. One alternative is to use your own serialization mechanism —  for example, concatenating the amount, a one character separator such as |, and the currency ISO code. However, there's another favored approach: using an open source serializer library such as JMS Serializer. Let's see an example of applying it when serializing a Money object:

$myMoney = new Money(999, new Currency('USD'));

$serializer = JMSSerializerSerializerBuilder::create()->build();
$jsonData = $serializer−>serialize(myMoney, 'json');

In order to unserialize the object, the process is straightforward:

$serializer = JMSSerializerSerializerBuilder::create()->build(); 
// ...
$
myMoney = $serializer−>deserialize(jsonData, 'Ddd', 'json');

With this example, you can refactor your Money class without having to update your database. JMS Serializer can be used in many different scenarios — for example, when working with REST APIs. An important feature is the ability to specify which attributes of an object should be omitted in the serialization process — for example, a password.

Check out the Mapping Reference and the Cookbook for more information. JMS Serializer is a must in any Domain-Driven Design project.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset