Events provide a simple observer pattern implementation, allowing you to subscribe and listen for various events that occur in your application. This cleanly decouples business operations (such as sending a welcome email after registration) from your HTTP controllers.
Generating Events & Listeners
Terminal • bash
php veldora make:event OrderPlaced
php veldora make:listener SendOrderConfirmationDefining the Event
Events are lightweight data containers holding the information related to the event:
example.php
PHP
// app/Events/OrderPlaced.php
namespace App\Events;
use App\Models\Order;
use Veldora\Framework\Events\Event;
class OrderPlaced extends Event
{
public function __construct(
public readonly Order $order
) {}
}Defining the Listener
Listeners handle the logic when an event is fired:
example.php
PHP
// app/Listeners/SendOrderConfirmation.php
namespace App\Listeners;
use Veldora\Framework\Events\Event;
use Veldora\Framework\Events\Listener;
use App\Mail\OrderInvoiceEmail;
class SendOrderConfirmation implements Listener
{
public function handle(Event $event): void
{
// Access event payload directly
$order = $event->order;
// Send email via mailer
mailer($order->customer_email)->send(new OrderInvoiceEmail($order));
log_info('Order invoice sent', ['order_id' => $order->id]);
}
}Registering Events and Listeners
Register your event-listener mappings in config/events.php:
example.php
PHP
return [
'listen' => [
\App\Events\OrderPlaced::class => [
\App\Listeners\SendOrderConfirmation::class,
\App\Listeners\UpdateInventoryStock::class,
],
\App\Events\UserRegistered::class => [
\App\Listeners\SendWelcomeNotification::class,
],
],
];Dispatching Events
Dispatch events anywhere in your application:
example.php
PHP
use App\Events\OrderPlaced;
// Option 1: Static dispatch method
OrderPlaced::dispatch($order);
// Option 2: Global event() helper
event(new OrderPlaced($order));