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 → clientAuth, 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:
getSubscribedEventsmaps event → method (+ optional priority)- Auto-wiring registers the subscriber when it implements
EventSubscriberInterfaceundersrc/ isMainRequest()avoids messing with sub-requests (fragments / ESI-ish cases)
Common kernel events
| Event | Typical use |
|---|---|
kernel.request | locale, early auth redirects, request tweaks |
kernel.controller | inspect/replace controller callable |
kernel.view | turn a non-Response return into a Response |
kernel.response | cookies, headers on the way out |
kernel.exception | custom error pages / API error JSON |
Compared to Laravel middleware
| Laravel | Symfony |
|---|---|
Middleware class + handle | Listener / Subscriber |
| Route middleware groups | Firewall + access control + custom subscribers |
$next($request) chain | Event 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,
-- ł.