handlers.rst 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. Handlers
  2. ========
  3. Introduction
  4. ------------
  5. Handlers allow you to change the serialization, or deserialization process
  6. for a single type/format combination.
  7. Handlers are simple callback which receive three arguments: the visitor,
  8. the data, and the type.
  9. Configuration
  10. -------------
  11. You can register any service as a handler by adding either the ``jms_serializer.handler``,
  12. or the ``jms_serializer.subscribing_handler``.
  13. Using ``jms_serializer.subscribing_handler``
  14. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  15. Using this tag, the configuration is contained in the handler itself which makes it
  16. easier to share with other users, and easier to set-up in general:
  17. .. code-block :: php
  18. <?php
  19. use JMS\SerializerBundle\Serializer\Handler\SubscribingHandlerInterface;
  20. use JMS\SerializerBundle\Serializer\GraphNavigator;
  21. use JMS\SerializerBundle\Serializer\JsonSerializationVisitor;
  22. class MyHandler implements SubscribingHandlerInterface
  23. {
  24. public static function getSubscribingMethods()
  25. {
  26. return array(
  27. array(
  28. 'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
  29. 'format' => 'json',
  30. 'type' => 'DateTime',
  31. 'method' => 'serializeDateTimeToJson',
  32. ),
  33. );
  34. }
  35. public function serializeDateTimeToJson(JsonSerializationVisitor $visitor, \DateTime $date, array $type)
  36. {
  37. return $date->format($type['params'][0]);
  38. }
  39. }
  40. .. code-block :: xml
  41. <service id="my_handler" class="MyHandler">
  42. <tag name="jms_serializer.subscribing_handler" />
  43. </service>
  44. Using ``jms_serializer.handler``
  45. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  46. If you have a handler like above, you can also wire it using the ``jms_serializer.handler`` tag:
  47. .. code-block :: xml
  48. <service id="my_handler" class="MyHandler" public="false">
  49. <tag name="jms_serializer.handler" type="DateTime" direction="serialization" format="json"
  50. method="serializeDateTimeToJson" />
  51. </service>
  52. .. tip ::
  53. The ``direction`` attribute is not required if you want to support both directions. Likewise can the
  54. ``method`` attribute be omitted, then a default using the scheme ``serializeTypeToFormat``,
  55. or ``deserializeTypeFromFormat`` will be used for serialization or deserialization
  56. respectively.