Know your components: A simple serializer with Symfony’s property access
Recetly, I needed to implement a quite simple serializer that would be used to prepare the entities from the database for indexing in ElasticSearch. I didn’t really need to get JSON or XML out of it, I only needed to transform my objects into arrays.
Instead of hacking around Symfony’s built-in Serializer or JMSSerializer (I’m not sure whether it’s simple to get just the data array out of those), I’ve decided I can do it in a lot more simple way just with PropertyAccess
.
PropertyAccess is a base Symfony component, commonly used in forms, but there’s nothing limiting its usage in different contexts. The whole aim of the component is to allow an easy way to read and write from and to objects and arrays. Its API is quite simple and straightforward:
use Symfony\Component\PropertyAccess\PropertyAccess;
$accessor = PropertyAccess::createPropertyAccessor();
$hello = array(
'greeted' =>
...