senenhermida.docs
  • Design Patterns
  • SOLID
  • PHP History
    • Late static binding
  • PHP Questions
  • Symfony
    • Service container
    • Event dispatcher
    • Security
    • Validation
    • Serializer
    • Http Kernel Component
    • Cache component
    • Symfony history
  • Algorithms
  • Leetcode
    • Codility
  • My CV
Powered by GitBook
On this page
  • Serializer
  • Serializer - deserialize update object
  1. Symfony

Serializer

Serializer

Serializer - deserialize update object

The Serializer component is meant to be used to turn objects into a specific format (XML, JSON, YAML, ...) and the other way around.

Normalizers (object < = > array)

Encoders (format(json, xml, csv, yaml…) < = > array)

Core Components:

  • Normalizers: Transform objects to and from arrays. Different normalizers are available for handling various types of objects.

  • Encoders: Convert arrays into specific formats (like JSON, XML, CSV) and decode these formats back into arrays.

  • Context: Provides additional settings or parameters to influence the serialization and deserialization processes.

  • Serialize (object ⇒ format)

use App\Model\Person;

$person = new Person();
$person->setName('foo');
$person->setAge(99);
$person->setSportsperson(false);

$jsonContent = $serializer->serialize($person, 'json');

// $jsonContent contains {"name":"foo","age":99,"sportsperson":false,"createdAt":null}
  • deserialize (format ⇒ object)

use App\Model\Person;

$data = <<<EOF
<person>
    <name>foo</name>
    <age>99</age>
    <sportsperson>false</sportsperson>
</person>
EOF;

$person = $serializer->deserialize($data, Person::class, 'xml');
  • deserialize can be used to update the object to

// ...
$person = new Person();
$person->setName('bar');
$person->setAge(99);
$person->setSportsperson(true);

$data = <<<EOF
<person>
    <name>foo</name>
    <age>69</age>
</person>
EOF;

$serializer->deserialize
							(
								$data, 
							  Person::class, 
								'xml', 
								[AbstractNormalizer::OBJECT_TO_POPULATE => $person]
);
// $person = App\Model\Person(name: 'foo', age: '69', sportsperson: true)

This is a common need when working with an ORM.

The AbstractNormalizer::OBJECT_TO_POPULATE is only used for the top level object

If that object is the root of a tree structure, all child elements that exist in the normalized data will be re-created with new instances.

When the AbstractObjectNormalizer::DEEP_OBJECT_TO_POPULATE option is set to true, existing children of the root OBJECT_TO_POPULATE are updated from the normalized data, instead of the denormalizer re-creating them. Note that DEEP_OBJECT_TO_POPULATE only works for single child objects, but not for arrays of objects. Those will still be replaced when present in the normalized data.

Context

Context refers to additional settings to pass to the serializer/deserializer

You can pass the context as follows:

$serializer->deserialize($someJson, Something::class, 'json', [
    DateTimeNormalizer::FORMAT_KEY => 'Y-m-d H:i:s',
]);

or

# config/packages/framework.yaml
framework:
    # ...
    serializer:
        default_context:
            enable_max_depth: true
            yaml_indentation: 2

or

#[Context([DateTimeNormalizer::FORMAT_KEY => 'Y-m-d'])]
public \DateTimeInterface $createdAt;

Features

  • attributes groups

to normalize/denormalize different attributes

class MyObj
{
    #[Groups(['group1', 'group2'])]
    public string $foo;
  • selecting specific attributes

$data = $serializer->normalize($user, null, [AbstractNormalizer::ATTRIBUTES => ['familyName', 'company' => ['name']]]);
  • ignoring attributes

$serializer->serialize($person, 'json', [AbstractNormalizer::IGNORED_ATTRIBUTES => ['age']]); // Output: {"name":"foo"}
  • Converting property names: custom, camelCase to snake_case

  • booleans: it works for has, get and can (App\Model\Person::isSportsperson())

  • callbacks: When serializing, you can set a callback to format a specific object property.

Normalizer

Normalizers in Symfony's Serializer are responsible for converting data between object and array (or scalar values) formats.

Object < = > array

object, getSet, property, datetime…

Always make sure to load the DateTimeNormalizer when serializing the DateTime or DateTimeImmutable classes to avoid excessive memory usage and exposing internal details.

Encoders

Encoders are components that handle the final stage of serialization — converting normalized data (arrays or scalar values) into a specific format (like JSON or XML) and vice versa.

array < = > formats

json, xml, csv, yaml

Circular Reference Handling:

  • The Serializer can handle circular references to prevent infinite loops during serialization, which is crucial in object graphs with bidirectional relationships.

PreviousValidationNextHttp Kernel Component