sajad torkamani

In a nutshell

Symfony provides an event system via the EventDispatcher component. A dispatcher dispatches certain events at specific times that listeners can listen and respond to.

For example, Symfony dispatches several events during the lifecycle of HTTP requests:

  • When a request has been created.
  • When a controller action is about to be executed.
  • When a response is ready to be sent.
  • When an exception has been thrown.

You can create listeners that listen to such events and execute some logic. For example, you might create a listener that listens to exceptions and sends you an email when an exception is thrown.

Many Symfony components like Security, Messenger, Workflow, and Mailer use events extensively – either by dispatching their own events or listening to events from other Symfony components. Third-party packages or bundles can also dispatch their own events to make their code extensible.

How to create custom subscribers

Let’s create a subscriber that listens to the Symfony\Component\HttpKernel\Event\ControllerEvent event, which is dispatched just before the controller is called.

1. Generate a subscriber

symfony console make:subscriber ControllerEventSubscriber

The command will ask you want event you want to listen to. Enter the event name (e.g., Symfony\Component\HttpKernel\Event\ControllerEvent).

2. Implement subscriber logic

The make command will generate a subscriber file: src/EventSubscriber/ControllerEventSubscriber.php:

<?php

namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;

class ControllerEventSubscriber implements EventSubscriberInterface
{
    public function onControllerEvent(ControllerEvent $event): void
    {
        // do something...
    }

    public static function getSubscribedEvents(): array
    {
        return [
            ControllerEvent::class => 'onControllerEvent',
        ];
    }
}

Add your custom logic to the onControllerEvent method. You have access to the event context (ControllerEvent).

List all registered event listeners

bin/console debug:event-dispatcher

List registered listeners for a particular event

bin/console debug:event-dispatcher <event-name>

For example, list all listeners for the kernel.controller event (see list of built-in Symfony events).

bin/console debug:event-dispatcher kernel.controller

Sources

Tagged: Symfony