Events and Event Listeners
Symfony triggers several events related to the kernelwhile processing the HTTP Request. Third-party bundles may also dispatch events, andyou can even dispatch from yourown code.
All the examples shown in this article use the same event for consistency purposes. In your own application, you can use any eventand even mix several of them in the same subscriber.
The most common way to listen to an event is to register an event listener:
Tip
Each event receives a slightly different type of $event
object. Forthe kernel.exception
event, it is ExceptionEvent
.Check out the to seewhat type of object each event provides.
New in version 4.3: The ExceptionEvent
class wasintroduced in Symfony 4.3. In previous versions it was calledSymfony\Component\HttpKernel\Event\GetResponseForExceptionEvent
.
Now that the class is created, you need to register it as a service andnotify Symfony that it is a "listener" on the kernel.exception
event byusing a special "tag":
- YAML
- # config/services.yaml
- services:
- App\EventListener\ExceptionListener:
- tags:
- - { name: kernel.event_listener, event: kernel.exception }
- XML
- PHP
- // config/services.php
- $container
- ->autowire(ExceptionListener::class)
- ->addTag('kernel.event_listener', ['event' => 'kernel.exception'])
- ;
- If the
kernel.event_listener
tag defines the attribute, that'sthe name of the method to be executed; - If no
method
attribute is defined, try to execute the method whose nameison
+ "camel-cased event name" (e.g.onKernelException()
method forthekernel.exception
event); - If that method is not defined either, try to execute the
__invoke()
magicmethod (which makes event listeners invokable); - If the
_invoke()
method is not defined either, throw an exception.
Note
There is an optional attribute for the kernel.event_listener
tag called, which is a positive or negative integer that defaults to 0
and it controls the order in which listeners are executed (the higher thenumber, the earlier a listener is executed). This is useful when you need toguarantee that one listener is executed before another. The priorities of theinternal Symfony listeners usually range from -255
to 255
but yourown listeners can use any positive or negative integer.
Creating an Event Subscriber
Another way to listen to events is via an event subscriber, which is a classthat defines one or more methods that listen to one or various events. The maindifference with the event listeners is that subscribers always know which eventsthey are listening to.
In a given subscriber, different methods can listen to the same event. The orderin which methods are executed is defined by the priority
parameter of eachmethod (the higher the number the earlier the method is called). To learn moreabout event subscribers, read The EventDispatcher Component.
The following example shows an event subscriber that defines several methods whichlisten to the same kernel.exception
event:
That's it! Your services.yaml
file should already be setup to load services fromthe EventSubscriber
directory. Symfony takes care of the rest.
Tip
A single page can make several requests (one master request, and then multiplesub-requests - typically when ).For the core Symfony events, you might need to check to see if the event is fora "master" request or a "sub request":
- // src/EventListener/RequestListener.php
- namespace App\EventListener;
- use Symfony\Component\HttpKernel\Event\RequestEvent;
- class RequestListener
- public function onKernelRequest(RequestEvent $event)
- {
- if (!$event->isMasterRequest()) {
- // don't do anything if it's not the master request
- return;
- }
- // ...
- }
- }
Certain things, like checking information on the real request, may not need tobe done on the sub-request listeners.
Listeners or Subscribers
Listeners and subscribers can be used in the same application indistinctly. Thedecision to use either of them is usually a matter of personal taste. However,there are some minor advantages for each of them:
- Subscribers are easier to reuse because the knowledge of the events is keptin the class rather than in the service definition. This is the reason whySymfony uses subscribers internally;
- Listeners are more flexible because bundles can enable or disable each ofthem conditionally depending on some configuration value.
You can find out what listeners are registered in the event dispatcherusing the console. To show all events and their listeners, run:
You can get registered listeners for a particular event by specifyingits name:
- $ php bin/console debug:event-dispatcher kernel.exception