Symfony 4 was released on November 30th.
Update now to the best Symfony ever!

You are browsing the Symfony 4 documentation, which changes significantly from Symfony 3.x. If your app doesn't use Symfony 4 yet, browse the Symfony 3.4 documentation.

How to Create your Custom Encoder

4.0 version

How to Create your Custom Encoder

The Serializer Component uses Normalizers to transform any data to an array. Then, by leveraging Encoders, that data can be converted into any data-structure (e.g. JSON).

The Component provides several built-in encoders that are described in their own section but you may want to use another structure that's not supported.

Creating a new encoder

Imagine you want to serialize and deserialize YAML. For that you'll have to create your own encoder that uses the Yaml Component:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
namespace App\Serializer;

use Symfony\Component\Serializer\Encoder\DecoderInterface;
use Symfony\Component\Serializer\Encoder\EncoderInterface;
use Symfony\Component\Yaml\Yaml;

class YamlEncoder implements EncoderInterface, DecoderInterface
{
    public function encode($data, $format, array $context = array())
    {
        return Yaml::dump($data);
    }

    public function supportsEncoding($format)
    {
        return 'yaml' === $format;
    }

    public function decode($data, $format, array $context = array())
    {
        return Yaml::parse($data);
    }

    public function supportsDecoding($format)
    {
        return 'yaml' === $format;
    }
}

Registering it in your app

If you use the Symfony Framework. then you probably want to register this encoder as a service in your app. If you're using the default services.yaml configuration, that's done automatically!

Tip

If you're not using autoconfigure, make sure to register your class as a service and tag it with serializer.encoder.

Now you'll be able to serialize and deserialize YAML!

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.