@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.
@lottie
To use the Symfony event dispatcher 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 17 |
use SymfonyComponentEventDispatcherEventSubscriberInterface; use SymfonyComponentSecurityCoreEventAuthenticationEvent; class UserLoginListener implements EventSubscriberInterface { public static function getSubscribedEvents() { return [ AuthenticationEvent::AUTHENTICATION_SUCCESS => 'onAuthenticationSuccess' ]; } public function onAuthenticationSuccess(AuthenticationEvent $event) { // Do something when the user logs in successfully } } |
1 2 3 4 |
services: AppEventListenerUserLoginListener: tags: - { name: kernel.event_subscriber } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
use SymfonyComponentEventDispatcherEventDispatcherInterface; use SymfonyComponentSecurityCoreEventAuthenticationEvent; class AuthenticationSuccessHandler implements AuthenticationSuccessHandlerInterface { private $eventDispatcher; public function __construct(EventDispatcherInterface $eventDispatcher) { $this->eventDispatcher = $eventDispatcher; } public function onAuthenticationSuccess(Request $request, TokenInterface $token) { // Dispatch the user.login event $this->eventDispatcher->dispatch(new AuthenticationEvent($token)); // Handle the authentication success // ... } } |
That's it! Your UserLoginListener
class will now be notified whenever the user.login
event is dispatched in your application.