handlers.rst 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. class MyHandler implements SubscribingHandlerInterface
  29. {
  30. public static function getSubscribingMethods()
  31. {
  32. return array(
  33. array(
  34. 'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
  35. 'format' => 'json',
  36. 'type' => 'DateTime',
  37. 'method' => 'serializeDateTimeToJson',
  38. ),
  39. );
  40. }
  41. public function serializeDateTimeToJson(JsonSerializationVisitor $visitor, \DateTime $date, array $type)
  42. {
  43. return $date->format($type['params'][0]);
  44. }
  45. }
  46. Also, this type of handler is registered via the builder object::
  47. $builder
  48. ->configureHandlers(function(JMS\Serializer\Handler\HandlerRegistry $registry) {
  49. $registry->registerSubscribingHandler(new MyHandler());
  50. })
  51. ;