1Handlers
2========
3
4Introduction
5------------
6Handlers allow you to change the serialization, or deserialization process
7for a single type/format combination.
8
9Handlers are simple callback which receive three arguments: the visitor,
10the data, and the type.
11
12Simple Callables
13----------------
14You can register simple callables on the builder object::
15
16    $builder
17        ->configureHandlers(function(JMS\Serializer\Handler\HandlerRegistry $registry) {
18            $registry->registerHandler('serialization', 'MyObject', 'json',
19                function($visitor, MyObject $obj, array $type) {
20                    return $obj->getName();
21                }
22            );
23        })
24    ;
25
26.. note ::
27
28        Be aware that when you call `configureHandlers` default handlers (like `DateHandler`)
29        won't be added and you will have to call `addDefaultHandlers` on the Builder
30
31Subscribing Handlers
32--------------------
33Subscribing handlers contain the configuration themselves which makes them easier to share with other users,
34and easier to set-up in general::
35
36    use JMS\Serializer\Handler\SubscribingHandlerInterface;
37    use JMS\Serializer\GraphNavigator;
38    use JMS\Serializer\JsonSerializationVisitor;
39    use JMS\Serializer\JsonDeserializationVisitor;
40    use JMS\Serializer\Context;
41
42    class MyHandler implements SubscribingHandlerInterface
43    {
44        public static function getSubscribingMethods()
45        {
46            return [
47                [
48                    'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
49                    'format' => 'json',
50                    'type' => 'DateTime',
51                    'method' => 'serializeDateTimeToJson',
52                ],
53                [
54                    'direction' => GraphNavigator::DIRECTION_DESERIALIZATION,
55                    'format' => 'json',
56                    'type' => 'DateTime',
57                    'method' => 'deserializeDateTimeToJson',
58                ],
59            ];
60        }
61
62        public function serializeDateTimeToJson(JsonSerializationVisitor $visitor, \DateTime $date, array $type, Context $context)
63        {
64            return $date->format($type['params'][0]);
65        }
66
67        public function deserializeDateTimeToJson(JsonDeserializationVisitor $visitor, $dateAsString, array $type, Context $context)
68        {
69            return new \DateTime($dateAsString);
70        }
71    }
72
73Also, this type of handler is registered via the builder object::
74
75    $builder
76        ->configureHandlers(function(JMS\Serializer\Handler\HandlerRegistry $registry) {
77            $registry->registerSubscribingHandler(new MyHandler());
78        })
79    ;
80
81