Skip to content

Events & subscribers ​

Laravel has middleware stacks. Symfony leans on the EventDispatcher - listeners and subscribers hooked into kernel (and other) events. Same "wrap the request" energy, different API.

Mental model ​

text
request → kernel.request listeners → controller → kernel.response listeners → client

Auth, locale, custom headers, early redirects - often live here.

Event subscriber ​

php
<?php

namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class LocaleSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::REQUEST => [['onKernelRequest', 20]],
        ];
    }

    public function onKernelRequest(RequestEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $request = $event->getRequest();
        // e.g. peek at _locale or a cookie - keep it tiny
        $request->setLocale($request->getPreferredLanguage(['en', 'pl']) ?? 'en');
    }
}

Comments for the code above:

  • getSubscribedEvents maps event → method (+ optional priority)
  • Auto-wiring registers the subscriber when it implements EventSubscriberInterface under src/
  • isMainRequest() avoids messing with sub-requests (fragments / ESI-ish cases)

Common kernel events ​

EventTypical use
kernel.requestlocale, early auth redirects, request tweaks
kernel.controllerinspect/replace controller callable
kernel.viewturn a non-Response return into a Response
kernel.responsecookies, headers on the way out
kernel.exceptioncustom error pages / API error JSON

Compared to Laravel middleware ​

LaravelSymfony
Middleware class + handleListener / Subscriber
Route middleware groupsFirewall + access control + custom subscribers
$next($request) chainEvent priorities + stop propagation

As you can see, you won't always write a subscriber for "auth" - Security does that - but when you need cross-cutting HTTP behavior, this is the knob.

Next: Doctrine entities and migrations.

Best,

-- ł.

Continues after /lab/php-tutorial-for-fe-devs/