Symfony events: kernel.request and your application's events
Symfony events: the kernel, Doctrine or the application announce what happens, and listeners react to it without the emitter knowing them.
// In the controller, once the dish is saved: $dispatcher->dispatch(new PlatAjoute($plat, $employe)); #[AsEventListener] // the event listened to is inferred from the type: App\Event\PlatAjoute final class InviterLesGuildes { public function __invoke(PlatAjoute $event): void { /* invite every guild */ } } #[AsEventListener] // priority 0: after the router (32), the route is known final class FermeLeLundi { public function __invoke(RequestEvent $event): void { /* $event->setResponse(…) */ } }
The kernel emits kernel.request, kernel.controller, kernel.response or kernel.exception on every request; Doctrine emits prePersist or postUpdate around writes; the application emits its own, plain objects passed to EventDispatcherInterface::dispatch(). The traps raise no error: a listener with a priority above 32 runs before the router and doesn't know the route yet; an event dispatched under an explicit name, dispatch($event, 'plat.ajoute'), no longer reaches those listening to its class name. debug:event-dispatcher shows who listens to what, and in which order.
The exercises have you fix a tavern where every piece works but nothing happens at the right time: a Monday closing that is ignored, a new dish nobody is told about, hand-picked slugs rewritten by a Doctrine listener. On the Laravel side, an exercise uses #[DebounceFor] to handle only the last event of a burst.
3 exercises work on this concept, by writing code in the browser.
In the tracks
- 🐉 Boss: the tavern turned upside down Symfony for PHP developers · chapter 9: The tavern's inner workings
In Practice
- Checking an event's contents with an array of properties assertDispatched() and assertPushed() accept an array of expected properties instead of a callback.
- Handling only the last event of a burst with #[DebounceFor] A queued listener with #[DebounceFor] waits for the burst to end and handles only the last event, where ShouldBeUnique kept the first one.
Related concepts
QueuesDebuggingDoctrine listenersService decorationCacheTesting