event_system.rst 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. Event System
  2. ============
  3. The serializer dispatches different events during the serialization, and
  4. deserialization process which you can use to hook in and alter the default
  5. behavior.
  6. Register an Event Listener, or Subscriber
  7. -----------------------------------------
  8. The difference between listeners, and subscribers is that listener do not know to which events they listen
  9. while subscribers contain that information. Thus, subscribers are easier to share, and re-use. Listeners
  10. on the other hand, can be simple callables and do not require a dedicated class.
  11. .. code-block :: php
  12. class MyEventSubscriber implements JMS\Serializer\EventDispatcher\EventSubscriberInterface
  13. {
  14. public static function getSubscribedEvents()
  15. {
  16. return array(
  17. array('event' => 'serializer.pre_serialize', 'method' => 'onPreSerialize'),
  18. );
  19. }
  20. public function onPreSerialize(JMS\Serializer\EventDispatcher\PreSerializeEvent $event)
  21. {
  22. // do something
  23. }
  24. }
  25. $builder
  26. ->configureListeners(function(JMS\Serializer\EventDispatcher\EventDispatcher $dispatcher) {
  27. $dispatcher->addListener('serializer.pre_serialize',
  28. function(JMS\Serializer\EventDispatcher\PreSerializeEvent $event) {
  29. // do something
  30. }
  31. );
  32. $dispatcher->addSubscriber(new MyEventSubscriber());
  33. })
  34. ;
  35. Events
  36. ------
  37. serializer.pre_serialize
  38. ~~~~~~~~~~~~~~~~~~~~~~~~
  39. This is dispatched before a type is visited. You have access to the visitor,
  40. data, and type. Listeners may modify the type that is being used for
  41. serialization.
  42. **Event Object**: ``JMS\Serializer\EventDispatcher\PreSerializeEvent``
  43. serializer.post_serialize
  44. ~~~~~~~~~~~~~~~~~~~~~~~~~
  45. This is dispatched right before a type is left. You can for example use this
  46. to add additional data for an object that you normally do not save inside
  47. objects such as links.
  48. **Event Object**: ``JMS\Serializer\EventDispatcher\ObjectEvent``
  49. serializer.pre_deserialize
  50. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  51. .. versionadded : 0.12
  52. Event was added
  53. This is dispatched before an object is deserialized. You can use this to
  54. modify submitted data, or modify the type that is being used for deserialization.
  55. **Event Object**: ``JMS\Serializer\EventDispatcher\PreDeserializeEvent``
  56. serializer.post_deserialize
  57. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  58. This is dispatched after a type is processed. You can use it to normalize
  59. submitted data if you require external services for example, or also to
  60. perform validation of the submitted data.
  61. **Event Object**: ``JMS\Serializer\EventDispatcher\ObjectEvent``