Event Dispatcher
Synchronous publish-subscribe within a single request. Decouples code that produces events from code that reacts to them.
- Dispatch an event object: `$dispatcher->dispatch(new UserRegistered($user))`.
- Listeners react: register via `#[AsEventListener(event: UserRegistered::class)]` on a class or method.
- Subscribers implement `EventSubscriberInterface::getSubscribedEvents()` — handy for grouping multiple events.
- Priority controls listener order; higher fires first. Listeners can call `$event->stopPropagation()`.
- Symfony itself uses the dispatcher for kernel events (request, response, exception, terminate).
- Event dispatcher is SYNCHRONOUS — for async, use Symfony Messenger instead.
final class UserRegistered
{
public function __construct(public readonly User $user) {}
}
#[AsEventListener]
final class SendWelcomeEmail
{
public function __invoke(UserRegistered $event): void { /* ... */ }
}
Common gotchas
- A throwing listener aborts the dispatch chain. Wrap in try/catch if a failure should not block other listeners.
- Don't use events for plain function calls. They shine when multiple unrelated bits of code need to react to the same fact.