Adding new formats

Core supports JSON and XML, as well as HAL-JSON. It is easy to add support for other formats.

Adding basic support

As explained in How the Serializer works, the serialization process has two parts, normalization and encoding.

If the array structure created by core's default Normalizers is acceptable for your format, then you can simply add an Encoder. For example, this is how support for YAML is added to core.

  1. Create an encoder
    Your Encoder should implement EncoderInterface.
  2. Register the encoder with the container
    Any service added to the container which is tagged with 'encoder' will be added to the encoder array which is passed into the Serializer. This code is placed in your module's Bundle class in the build() method.
    $container->register('serializer.encoder.yaml', 'Drupal\Core\Serialization\YamlEncoder')

Changing the way Serializer handles entities

Core supports serialization for content entities, their fields, and field items. It is easy to add support for other classes, and also to modify the way Serializer handles classes.

--To be completed--

How the Serializer works

The Serialization API depends on Symfony's Serializer component.

Serializer's separation of concerns

The serializer splits the work into two steps. First, it will normalize the object to an array. Then it will encode that array into the requested format.

Diagram showing object transformed to array by normalize method and array transformed to string by encode

This work is split across two interfaces, the NormalizerInterface and the EncoderInterface. When a Serializer is created, all of the Normalizer objects which might be necessary to handle the data are passed in, as well as all of the relevant Encoder objects.

$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ComplexDataNormalizer(), new ListNormalizer(), new TypedDataNormalizer());

$serializer = new Serializer($normalizers, $encoders);

Serialization API in Drupal 8

Drupal 8 can output JSON and XML versions of data using the Serialization API. Modules can add new serialization formats, as core's HAL (#1924854: [META] Hypertext Application Language (HAL) support) module will.

Serializing data

To serialize data, get the serializer from the container.

Subscribe with RSS Subscribe to RSS - serialization