Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 62 ยท Events, Messaging and Console

Events and Listeners

Hook into Symfony with the EventDispatcher: kernel events, listeners, subscribers, #[AsEventListener], priorities and custom events, with runnable stand-ins.

Sometimes code needs to run around something else, without that something knowing about it: add a header to every response, log every failed login, send a receipt after an order is placed. If you put all of that inside one controller or service, the code becomes a pile of unrelated jobs. The event dispatcher solves this with the observer pattern: one piece of code announces "this happened", and any number of listeners react.

Symfony is built on this idea. The framework itself dispatches events while it turns a request into a response, and your application can dispatch its own. This lesson explains events, listeners and subscribers, shows the kernel events in order, and rebuilds the dispatcher in plain PHP so you can run it. It assumes you have seen the request lifecycle and the service container.

The three parts

  • An event is a small object that describes what happened and carries the data listeners need. Custom events extend Symfony\Contracts\EventDispatcher\Event.
  • A dispatcher is the service (EventDispatcherInterface) that you call with dispatch($event).
  • A listener is any callable that wants to hear about a certain event. A subscriber is a class that declares the events it listens to itself.
flowchart LR
    S["OrderService<br/>dispatch(new OrderPlaced)"] --> D["EventDispatcher"]
    D -->|"priority 10"| L1["ReserveStockListener"]
    D -->|"priority 0"| L2["ReceiptSubscriber"]
    D -->|"priority -5"| L3["AuditLogListener"]

The dispatcher calls listeners in order of priority; the code that dispatched the event never refers to them.

An event's name is a string. Since Symfony 4.3 the usual name is simply the event's class name (OrderPlaced::class), which gives you autocomplete and refactoring support. The framework's own events keep their historic string names, such as kernel.request, and the same events can also be addressed by class.

Kernel events in order

While handling a request, HttpKernel dispatches a series of events. These are the ones you will use most:

Event name Event class When it fires
kernel.request RequestEvent Before routing finishes; a listener may set a response and skip the controller
kernel.controller ControllerEvent After the controller is chosen, before it runs
kernel.controller_arguments ControllerArgumentsEvent After arguments are resolved
kernel.view ViewEvent Only if the controller returned something that is not a Response
kernel.response ResponseEvent Always, just before the response is returned
kernel.finish_request FinishRequestEvent After the response is built
kernel.terminate TerminateEvent After the response has been sent to the client (with PHP-FPM)
kernel.exception ExceptionEvent When anything throws

Symfony's own routing, security and session features are listeners on these events. The firewall, for instance, listens on kernel.request and can answer with a redirect to the login page before your controller is ever called.

Because sub-requests exist (for example when a template renders another controller), kernel event listeners usually begin with if (!$event->isMainRequest()) { return; }.

Writing a listener with an attribute

The modern way is the #[AsEventListener] attribute. Put it on a class with an __invoke() method, or on any method:

PHP
// src/EventListener/SecurityHeadersListener.php (real Symfony, read-only)
namespace App\EventListener;

use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpKernel\Event\ResponseEvent;

#[AsEventListener(event: ResponseEvent::class, priority: -10)]
final class SecurityHeadersListener
{
    public function __invoke(ResponseEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $event->getResponse()->headers->set('X-Content-Type-Options', 'nosniff');
    }
}

With autoconfiguration the class is registered as a listener as soon as it exists. If you leave out event:, Symfony reads it from the type of the first argument of the method. To listen to several events in one class, put the attribute on several methods:

PHP
// real Symfony, read-only
final class LoginAuditListener
{
    #[AsEventListener]
    public function onSuccess(LoginSuccessEvent $event): void { /* ... */ }

    #[AsEventListener]
    public function onFailure(LoginFailureEvent $event): void { /* ... */ }
}

The older route is still common in tutorials and bundles: tag the service kernel.event_listener in services.yaml. It does the same thing with more typing.

Subscribers

A subscriber implements EventSubscriberInterface and returns a map from event to method in a static method. The knowledge of "what do I listen to" lives inside the class:

PHP
// src/EventSubscriber/ExceptionSubscriber.php (real Symfony, read-only)
namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;

final class ExceptionSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::EXCEPTION => ['onException', 0],
        ];
    }

    public function onException(ExceptionEvent $event): void
    {
        $event->setResponse(new JsonResponse(['error' => 'Something went wrong'], 500));
    }
}

The map accepts three shapes: 'event' => 'method', 'event' => ['method', priority] and 'event' => [['methodA', 10], ['methodB', -5]] for several methods. Listeners and subscribers are equally good. Attributes are shorter; subscribers keep related listeners together and are easy to move into a reusable bundle.

Priority and stopping propagation

Listeners for one event run from the highest priority number to the lowest; the default is 0, and listeners with equal priority run in the order they were registered. Symfony's own listeners use priorities too, so a number such as 8 or -10 is meaningful. Run php bin/console debug:event-dispatcher kernel.request to see the real order in your application.

Events that extend Event also support $event->stopPropagation(). Once called, the dispatcher skips the remaining listeners. Use it rarely: it creates hidden coupling, and Symfony's kernel events use it mostly when a response has been set.

Running a dispatcher

Here is a stand-in dispatcher with the same concepts: events as objects, class names as event names, priorities, subscribers and propagation stopping. It is not Symfony's implementation, but the behaviour you see matches the description above.

PHP A dispatcher with priorities and a subscriber (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The small order passes through stock, receipt and audit in priority order (10, 0, -5). The large one is caught by the priority-100 listener, which stops propagation, so none of the other three run. This is exactly how a high-priority guard can short-circuit later work, and also why you should document any listener that stops propagation.

A tiny kernel driven by events

The real HttpKernel is mostly a sequence of dispatches around a controller call. This stand-in reproduces the shape with three events: a request event whose listener may answer early, a response event that decorates every response, and an exception event that turns errors into pages.

PHP A mini kernel with request, response and exception events (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The second request never reaches its controller: the high-priority listener sets a 403 response and stops the request event. The unknown path and the buggy controller both end up in the exception listener, which chooses a status. Every response, no matter how it was produced, passes through the response event and gets its header. The line marked with * is the request that carried a user.

Designing with events

  • Use events for side effects, not for the main job. The service that places an order should save the order; "send a receipt" and "write an audit entry" can be listeners.
  • Name events in the past tense (OrderPlaced, UserRegistered): they report something that already happened.
  • Keep listeners fast. They run inside the request. If the work is slow or can fail, have the listener dispatch a message to Messenger so it runs in a worker.
  • Do not hide business rules in listeners. If a rule must always hold, put it in a service where it is visible.
  • Doctrine has its own events (lifecycle callbacks and entity listeners), covered with entities. They use a similar idea but a different dispatcher.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In which order does the dispatcher call listeners for one event?

    Higher numbers run first. The default priority is 0, and listeners with the same priority run in registration order.
  2. 2. What is the difference between a listener and a subscriber?

    Both react to events. A subscriber carries its own event map; a listener is attached through an attribute or a service tag.
  3. 3. A listener on kernel.request calls $event->setResponse(...). What happens next?

    A response set during kernel.request short-circuits routing and the controller. The kernel.response listeners still run on it.
  4. 4. Why do kernel listeners often start with isMainRequest()?

    Rendering a controller from a template creates a sub-request that triggers the same events. Checking isMainRequest() avoids doing the work twice.
  5. 5. A listener must send an email that can take several seconds. What is the better design?

    Listeners run inside the request. Slow or failure-prone work belongs in an asynchronous handler.

Summary

  • An event is an object, a dispatcher announces it and listeners or subscribers react; the dispatching code does not know who listens.
  • The kernel dispatches kernel.request, kernel.controller, kernel.view, kernel.response, kernel.exception, kernel.terminate and more; much of Symfony itself is built from listeners on them.
  • Register listeners with #[AsEventListener] (or a tagged service) and subscribers with EventSubscriberInterface::getSubscribedEvents().
  • Higher priority runs first; stopPropagation() skips the rest and should be used sparingly.
  • Keep listeners quick and move slow work to Messenger.

Next up: Messenger: Messages and Handlers.