Event System
Event System
Hazaar includes a simple yet powerful event dispatching system that allows different parts of your application to interact without being tightly coupled. This is achieved through the use of events and listeners.
Introduction
The core idea is that certain actions within your application (like a user logging in, an order being placed, etc.) can trigger an "event". Other parts of the application can "listen" for these events and react accordingly (e.g., send a welcome email when a user registers, update inventory when an order is placed).
This system supports both immediate event handling and queued event handling. Queued events are useful for tasks that can be deferred, such as sending emails or notifications, which might otherwise slow down the primary user request.
Defining Events
Events are simple PHP classes that typically hold data related to the event that occurred. To make an event class easily dispatchable, use the Hazaar\Events\Dispatchable trait.
<?php
namespace App\Events;
use Hazaar\Events\Dispatchable;
class UserRegisteredEvent
{
use Dispatchable;
public string $userId;
public string $email;
public function __construct(string $userId, string $email)
{
$this->userId = $userId;
$this->email = $email;
}
}The Dispatchable trait provides a static dispatch() method, allowing you to trigger the event like this:
UserRegisteredEvent::dispatch('user-123', '[email protected]');Defining Listeners
Listeners are classes that contain the logic to handle specific events. A listener class must have a public handle method. The type hint of the first parameter of the handle method determines which event the listener will react to.
<?php
namespace App\Listeners;
use App\Events\UserRegisteredEvent;
class SendWelcomeEmailListener
{
public function handle(UserRegisteredEvent $event): void
{
// Logic to send a welcome email
echo "Sending welcome email to {$event->email} for user {$event->userId}\n";
// mail($event->email, 'Welcome!', '...');
}
}When a UserRegisteredEvent is dispatched, the handle method of SendWelcomeEmailListener (if registered) will be called automatically, receiving the UserRegisteredEvent object as an argument.
Registering Listeners
Before a listener can handle an event, it must be registered with the event dispatcher. There are two ways to do it.
Automatic Registration
At bootstrap the application looks for a listeners directory inside your app directory. If it exists, every .php file in it is included and, for each file, the class App\Listeners\<FileName> is instantiated and registered:
app
├─ Events
│ └─ UserRegisteredEvent.php # App\Events\UserRegisteredEvent
├─ Listeners
│ ├─ SendWelcomeEmailListener.php # App\Listeners\SendWelcomeEmailListener
│ └─ LoginAudit.php # App\Listeners\LoginAudit
└─ ...The rules are:
- The directory is the
paths.listenersetting, which defaults toListeners. If that directory doesn't exist, the older lowercaselistenersis used instead, so existing apps keep working. Only the first one found is scanned. - Files that aren't
.phpare ignored. - The class must be in the
App\Listenersnamespace and named after its file. - Its constructor must take no arguments.
- Files whose class doesn't exist after including them are skipped silently, as are listeners whose
handle()first parameter isn't a class type. If a listener never fires, check these first.
The scan happens once per process, in Application::bootstrap(), after your bootstrap.php has run.
Manual Registration
Register listener instances yourself, typically in app/bootstrap.php:
<?php
use Hazaar\Events\Event;
use App\Listeners\SendWelcomeEmailListener;
// Register an instance of the listener
Event::listen(new SendWelcomeEmailListener());
// Or using the EventDispatcher directly
Hazaar\Events\EventDispatcher::getInstance()->addListener(new SendWelcomeEmailListener());Manual registration lets you pass constructor arguments, such as configuration.
Built-in Events
The framework dispatches these events through the same dispatcher. Listen for them like any other event.
| Event class | When it fires | Properties |
|---|---|---|
Hazaar\Auth\Event\LoginSucceeded | After a successful Adapter::authenticate(), and after Adapter::login() (used for passkeys) | identity (string), data (array, the user data stored in the session) |
Hazaar\Auth\Event\LoginFailed | When Adapter::authenticate() rejects the credentials | identity (string, as submitted) |
authenticateAs() and token refreshes don't dispatch events. Both event classes are readonly, so listeners can't change them.
// app/Listeners/LoginAudit.php
namespace App\Listeners;
use Hazaar\Auth\Event\LoginFailed;
class LoginAudit
{
public function handle(LoginFailed $event): void
{
error_log("Failed login for {$event->identity}");
}
}Using Queued Listeners
Sometimes, you don't want a listener to execute immediately when an event is dispatched, especially if the listener performs a time-consuming task like sending an email or calling an external API. This could slow down the response to the user.
For these scenarios, you can make a listener "queuable". Queued listeners are executed only when the event queue is processed, which the application does after the response has been written.
To make a listener queuable, implement the Hazaar\Events\Interface\Queuable marker interface. It has no methods.
<?php
namespace App\Listeners;
use App\Events\UserRegisteredEvent;
use Hazaar\Events\Interface\Queuable;
use Hazaar\Mail\Adapter as Mail;
class SendWelcomeEmailListener implements Queuable
{
public function handle(UserRegisteredEvent $event): void
{
$mail = new Mail();
$mail->addTo($event->email);
$mail->setSubject('Welcome!');
$mail->setBodyHTML('<p>Thanks for signing up.</p>');
$mail->send();
}
}Now, when UserRegisteredEvent::dispatch() is called, SendWelcomeEmailListener::handle() does not run straight away. The event is added to an in-memory queue, and the email is sent once the response has been written. See Mail for configuring the mailer.
When the Queue Runs
At the end of Application::run(), in this order:
- The response is written and the output buffer is flushed.
Event::dispatchQueue()runs every queued listener.app/complete.phpruns, if you have one.
The queue is flushed on every request, whether or not your app has a listeners directory, so listeners registered by hand in bootstrap.php run too.
Things to know:
- The queue is in memory. It isn't a job queue: nothing is persisted, there are no retries, and if the process dies the queued events are lost. For work that must happen, or that takes more than a few seconds, hand it to Warlock from the listener (for example with
delay()), or use a real job queue. - The client doesn't wait. Before flushing, the framework calls
fastcgi_finish_request()where PHP provides it (PHP-FPM), so the client's connection is released and queued listeners don't delay the response. Under other servers, such asphp -S, the connection stays open until they finish. Either way a worker is busy until the last listener returns, so keep them short. - Each listener runs once. A queued listener runs once per dispatched event, and a listener that isn't queued runs at dispatch time only, never again at flush time. An event can have both kinds.
- Exceptions are logged and stop the flush. An exception from a queued listener can't change the response, and the framework logs it as an error. It also ends the flush: the remaining queued listeners for that event are dropped, and queued listeners for other events wait for the next flush (the next request in a long-running worker, never under PHP-FPM). Catch and log errors inside
handle()so one failure doesn't affect the others. - CLI and Warlock. Nothing flushes the queue in console commands or Warlock processes. Call
Event::dispatchQueue()yourself there, or use non-queued listeners. - FrankenPHP worker mode. The dispatcher and the listener objects are singletons that live for the whole worker, and listeners are registered once, at bootstrap. The queue is flushed at the end of each request, so events don't carry over, but any property you set on a listener does. Keep listeners stateless.
Dispatching Queued Events Manually
To process the event queue manually and execute the handle methods of queued listeners, you need to call Event::dispatchQueue(). This method can be called in two ways:
Process All Queued Events: Call
Event::dispatchQueue()without any arguments to process all events in the queue regardless of their type.// Process all queued events and clear the entire queue Event::dispatchQueue();Process Specific Event Types: Call
Event::dispatchQueue()with the fully qualified class name of an event to process only events of that specific type.// Process only UserRegisteredEvent instances in the queue Event::dispatchQueue(UserRegisteredEvent::class);
Here's a complete example demonstrating both approaches:
<?php
use Hazaar\Events\Event;
use App\Events\UserRegisteredEvent;
use App\Events\OrderPlacedEvent;
use App\Listeners\SendWelcomeEmailListener;
use App\Listeners\UpdateInventoryQueuedListener;
// Register queued listeners
Event::listen(new SendWelcomeEmailListener()); // Handles UserRegisteredEvent
Event::listen(new UpdateInventoryQueuedListener()); // Handles OrderPlacedEvent
// Dispatch different types of events
$userEvent = UserRegisteredEvent::dispatch('user-123', '[email protected]');
$orderEvent = OrderPlacedEvent::dispatch('order-456', 99.99);
// At this point, both events are queued but not processed
// Process only user registration events
echo "Processing only user registration events...\n";
Event::dispatchQueue(UserRegisteredEvent::class);
// Now SendWelcomeEmailListener has processed $userEvent
// But $orderEvent is still in the queue
// Process the remaining events (the order event)
echo "Processing remaining events...\n";
Event::dispatchQueue();
// Now UpdateInventoryQueuedListener has processed $orderEventThe ability to selectively process specific event types can be useful when you want to prioritize certain operations or manage resource usage more carefully. In most cases, however, calling Event::dispatchQueue() without arguments at the end of the request lifecycle is the most common pattern.
In a Hazaar web application you don't usually need to call it at all: the framework flushes the queue at the end of each request, as described in When the Queue Runs.