Event-driven architecture helps separate parts of your code so they don't depend on each other directly. This makes your app easier to change and grow.
Why event-driven architecture decouples code in Laravel
class EventName { // Event data and methods } class ListenerName { public function handle(EventName $event) { // Code to run when event fires } } // To fire event: event(new EventName());
Events are simple classes that hold information about something that happened.
Listeners are classes that react to those events by running code in the handle method.
<?php
namespace App\Events;
class UserRegistered {
public $user;
public function __construct($user) {
$this->user = $user;
}
}UserRegistered event fires.<?php
namespace App\Listeners;
use App\Events\UserRegistered;
class SendWelcomeEmail {
public function handle(UserRegistered $event) {
// Send email to $event->user
}
}// Firing the event
$user = User::find(1);
event(new UserRegistered($user));This example shows an event OrderPlaced carrying an order ID. The listener NotifyWarehouse reacts by printing a message. This keeps the order logic separate from notification logic.
<?php namespace App\Events; class OrderPlaced { public $orderId; public function __construct(int $orderId) { $this->orderId = $orderId; } } namespace App\Listeners; use App\Events\OrderPlaced; class NotifyWarehouse { public function handle(OrderPlaced $event) { echo "Notify warehouse about order #" . $event->orderId . "\n"; } } // Simulate event firing and listener handling $orderId = 123; $event = new OrderPlaced($orderId); $listener = new NotifyWarehouse(); $listener->handle($event);
Events and listeners help keep your code clean by separating what happens from how it happens.
Laravel automatically finds and runs listeners if you register them in EventServiceProvider.
Using events makes it easier to add new features without changing existing code.
Event-driven architecture separates code by using events and listeners.
This separation makes your app easier to maintain and extend.
Laravel provides simple tools to create and use events and listeners.