laravel
Junior
What is the difference between events and listeners?
Short Answer
Events represent something that happened. Listeners react to events. This decouples the triggering code from the side effects.
Detailed Answer
Events and Listeners:
Events:
- Represent something that happened (UserRegistered, OrderPlaced)
- Carry data about what happened
- Dispatched with event() helper or Dispatchable trait
- Decouple the main action from side effects
Listeners:
- React to specific events
- Perform side effects (send email, update cache, sync data)
- One event can have multiple listeners
- Can be queued for background processing
Benefits:
- Open/Closed principle: add new behaviors without modifying existing code
- Testability: test listeners independently
- Decoupling: core logic doesn't know about side effects
- Multiple responses to one event without code changes
Code Example
Example
<?php
// Event class
class OrderPlaced
{
use Dispatchable, SerializesModels;
public function __construct(
public readonly Order $order
) {}
}
// Listener
class SendOrderConfirmation
{
public function __construct(private Mailer $mailer) {}
public function handle(OrderPlaced $event): void
{
$this->mailer->to($event->order->user->email)
->send(new OrderConfirmationMail($event->order));
}
}
// EventServiceProvider
protected $listen = [
OrderPlaced::class => [
SendOrderConfirmation::class,
UpdateInventory::class,
NotifyAdmin::class,
],
];
event(new OrderPlaced($order)); // Triggers all 3 listeners
Interview Tip
Explain that listeners can be queued: "A listener can implement ShouldQueue for background processing, like sending emails without slowing the request."