How to Create your Custom Encoder

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 the serializer component 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. // src/Serializer/YamlEncoder.php
  2. namespace App\Serializer;
  3. use Symfony\Component\Serializer\Encoder\DecoderInterface;
  4. use Symfony\Component\Serializer\Encoder\EncoderInterface;
  5. use Symfony\Component\Yaml\Yaml;
  6. class YamlEncoder implements EncoderInterface, DecoderInterface
  7. {
  8. public function encode($data, $format, array $context = [])
  9. {
  10. return Yaml::dump($data);
  11. }
  12. public function supportsEncoding($format)
  13. {
  14. return 'yaml' === $format;
  15. }
  16. public function decode($data, $format, array $context = [])
  17. {
  18. return Yaml::parse($data);
  19. }
  20. public function supportsDecoding($format)
  21. {
  22. return 'yaml' === $format;
  23. }
  24. }

Tip

If you need access to $context in your supportsDecoding or supportsEncoding method, make sure to implement Symfony\Component\Serializer\Encoder\ContextAwareDecoderInterface or Symfony\Component\Serializer\Encoder\ContextAwareEncoderInterface accordingly.

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.