extending.rst 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. Extending The Serializer
  2. ========================
  3. This document details the different extension points, and how you can utilize
  4. them to change the default behavior of the serializer.
  5. Custom De-/Serialization Handlers
  6. ---------------------------------
  7. This allows you to change the way of how a specifc type is being de-/serialized.
  8. Any handler must implement either the ``SerializationHandlerInterface``, or
  9. ``DeserializationHandlerInterface``, or both. This bundle already comes with
  10. some handlers which you find in the Serializer/Handler folder, and which you
  11. can use as a starting point.
  12. Custom handlers are normal services, and thus can have dependencies on any
  13. other service available in the dependency injection container.
  14. After you have written your handler, you can write a service definition. Such
  15. as the following::
  16. <service id="acme_foo.serializer.my_handler"
  17. class="Acme\FooBundle\Serializer\MyHandler"
  18. public="false"
  19. abstract="true" />
  20. Note that we have declared this definition abstract, we will later see
  21. why. At the moment, do not worry too much about this.
  22. What is left to do is to publish our new handler to this bundle. So it gets
  23. picked up, and wired with the correct serializer. In order to do this, this
  24. bundle uses a configuration system similar to that of the SecurityBundle. Each
  25. handler needs a corresponding factory::
  26. <?php
  27. namespace Acme\FooBundle\DependencyInjection\Factory;
  28. use JMS\SerializerBundle\DependencyInjection\SerializerFactoryInterface;
  29. class MyHandlerFactory implements SerializerFactoryInterface
  30. {
  31. public function getKey()
  32. {
  33. return 'acme_foo_my';
  34. }
  35. public function addConfiguration(ArrayNodeDefinition $builder)
  36. {
  37. }
  38. public function process(ContainerBuilder $container, array $config, $id)
  39. {
  40. }
  41. }
  42. This factory is responsible for setting up the configuration for your handler
  43. in the ``addConfiguration`` method, and then process that configuration in the
  44. ``process`` method.
  45. The last thing left to do, is to add this factory to this bundle. This is
  46. done by adding a ``configureSerializerExtension`` to your bundle class::
  47. <?php
  48. namespace Acme\FooBundle;
  49. use Acme\FooBundle\DependencyInjection\Factory\FooFactory;
  50. use JMS\SerializerBundle\DependencyInjection\JMSSerializerExtension;
  51. use Symfony\Component\HttpKernel\Bundle\Bundle;
  52. class AcmeFooBundle extends Bundle
  53. {
  54. public function configureSerializerExtension(JMSSerializerExtension $ext)
  55. {
  56. $ext->addFactory(new FooFactory());
  57. }
  58. }