Symfony EventDispatcher: listeners, subscribers and order

Symfony's EventDispatcher announces an event to all its listeners, one after the other: you add behaviour without touching the code that emits it.

// Until now: priorities chosen by reading the other listeners' priorities.
#[AsEventListener(priority: 20)]
class AppliquerCodePromoListener { /* … */ }

#[AsEventListener(priority: 10)]
class CalculerTotalListener { /* … */ }

// Since Symfony 8.2: the order is expressed by names.
#[AsEventListener(after: AppliquerCodePromoListener::class, before: CalculerTotalListener::class)]
class FraisDePortListener
{
    public function __invoke(CommandePassee $commande): void { /* … */ }
}

Symfony's kernel emits its own events on every request, and an application can dispatch its own. A listener is declared with #[AsEventListener], a subscriber implements EventSubscriberInterface and lists its events in getSubscribedEvents(). The trap is about order: until now it was set with integer priorities, chosen by reading the other listeners' priorities, and renumbered the day a step has to slip in between two. bin/console debug:event-dispatcher shows the actual order.

The exercises for this concept are about Symfony 8.2: writing getSubscribedEvents() with named keys, then replacing priorities with before and after constraints between listeners.

2 exercises work on this concept, by writing code in the browser.

In Practice