Advertisement
Intermediate PHP, Symfony Framework Essentials

What are Symfony events and event listeners, and how do they let different parts of an application react to something happening without tightly coupling that logic together?

Short answer

Symfony's event system lets one part of an application dispatch an event at a meaningful moment, such as right after a new user registers, without needing to know anything about what, if anything, should happen in response, and separately, one or more event listeners or…

Save PHP mock interview
Advertisement
AModel answer
Symfony's event system lets one part of an application dispatch an event at a meaningful moment, such as right after a new user registers, without needing to know anything about what, if anything, should happen in response, and separately, one or more event listeners or subscribers can be registered to react to that specific event whenever it occurs, such as sending a welcome email or logging the registration, which keeps the original registration logic focused purely on registering the user, while any additional side effects remain cleanly separated and easy to add or remove independently.
class UserRegisteredEvent extends Event
{
    public function __construct(public readonly User $user) {}
}

// Listener
public function onUserRegistered(UserRegisteredEvent $event): void
{
    $this->mailer->sendWelcomeEmail($event->user);
}
Real-world example
A Symfony application dispatches a UserRegisteredEvent right after successfully creating a new user account, allowing a completely separate listener to send a welcome email without the original registration code needing any direct knowledge of the mailer at all.
Likely follow-ups
  • What is the difference between an event listener and an event subscriber in Symfony?
  • Can a single event have multiple listeners responding to it, and if so, does the order in which they run matter?
Related topics