handlers.rst 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. Simple Callables
  10. ----------------
  11. You can register simple callables on the builder object::
  12. $builder
  13. ->configureHandlers(function(JMS\Serializer\Handler\HandlerRegistry $registry) {
  14. $registry->registerHandler('serialization', 'MyObject', 'json',
  15. function($visitor, MyObject $obj, array $type) {
  16. return $obj->getName();
  17. }
  18. );
  19. })
  20. ;
  21. Subscribing Handlers
  22. --------------------
  23. Subscribing handlers contain the configuration themselves which makes them easier to share with other users,
  24. and easier to set-up in general::
  25. use JMS\Serializer\Handler\SubscribingHandlerInterface;
  26. use JMS\Serializer\GraphNavigator;
  27. use JMS\Serializer\JsonSerializationVisitor;
  28. use JMS\Serializer\Context;
  29. class MyHandler implements SubscribingHandlerInterface
  30. {
  31. public static function getSubscribingMethods()
  32. {
  33. return array(
  34. array(
  35. 'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
  36. 'format' => 'json',
  37. 'type' => 'DateTime',
  38. 'method' => 'serializeDateTimeToJson',
  39. ),
  40. );
  41. }
  42. public function serializeDateTimeToJson(JsonSerializationVisitor $visitor, \DateTime $date, array $type, Context $context)
  43. {
  44. return $date->format($type['params'][0]);
  45. }
  46. }
  47. Also, this type of handler is registered via the builder object::
  48. $builder
  49. ->configureHandlers(function(JMS\Serializer\Handler\HandlerRegistry $registry) {
  50. $registry->registerSubscribingHandler(new MyHandler());
  51. })
  52. ;