@lottie
The Symfony event dispatcher is a powerful tool that allows you to manage and dispatch events within your application. To use it to listen to events, you need to follow these steps:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
use SymfonyComponentEventDispatcherEventSubscriberInterface; class MyEventSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents() { return [ 'my.event.name' => 'onMyEvent', ]; } public function onMyEvent($event) { // Do something when the 'my.event.name' event is dispatched } } |
In the getSubscribedEvents()
method, you define which events you want to listen to and which method should be called when that event is dispatched. In this example, the onMyEvent()
method will be called when the 'my.event.name'
event is dispatched.
1 2 3 4 5 |
services: my.event.subscriber: class: AppEventSubscriberMyEventSubscriber tags: - { name: kernel.event_subscriber } |
In this example, we have registered the MyEventSubscriber
class as a service and tagged it with kernel.event_subscriber
so that Symfony knows to register it as an event subscriber.
That's it! Now your event subscriber is registered and will listen to the events you defined in the getSubscribedEvents()
method. When an event is dispatched, the corresponding method in your event subscriber will be called, allowing you to perform any actions you need to based on that event.