Events and listeners
An event class
An event is a small object that announces that something happened, such as an order being placed. It carries only the data listeners need and no behavior of its own.
Constructor promotion keeps the class to a few lines: declare the payload as a promoted property and stop there.
class OrderPlaced { public function __construct(public int $orderId) { } }
A listener
A listener reacts to one event with a handle method that receives the event object. One event can wake many listeners, and each one handles a single side effect such as sending mail.
Keep listeners small so each side effect stays easy to test in isolation.
class SendOrderEmail { public function handle(OrderPlaced $event): void { echo $event->orderId; } }
Dispatch it
Fire the event with the global event helper wherever the action happens, usually right after the order row is stored. Laravel finds the registered listeners and calls each handle method in turn.
The dispatching code never names the listeners, so new reactions can be added without touching it.
event(new OrderPlaced(42));
Queued listeners note
Slow reactions such as mail belong in the background. A listener that implements the ShouldQueue contract runs on a queue worker instead of inside the web request.
The handle code stays exactly the same, only the timing changes from now to soon.
use Illuminate\Contracts\Queue\ShouldQueue; class SendOrderEmail implements ShouldQueue { public function handle(OrderPlaced $event): void { echo $event->orderId; } }
Next: Queues
Article author: Arthur Isaev