Application services
Events
Taphra\Event is an in-process event bus: one part of the app announces that something happened, other parts react to it. Listeners run synchronously, inside the same request, before emit() returns. For slow work (sending mail, calling an API), have the listener push a job to a queue.
Listening and emitting
#Register a listener with Event::on() and announce the event with Event::emit(). Event names are free-form strings; a dotted noun.verb style (order.paid, user.signed_up) works well with wildcards.
use Taphra\Event;
Event::on('order.paid', function (array $order): void {
echo "Receipt for order {$order['id']}\n";
});
$order = ['id' => 42, 'total' => 1990];
$called = Event::emit('order.paid', [$order]); // prints "Receipt for order 42"
// $called === 1: emit() returns the number of listeners it calledHow the payload reaches the listener
#emit(string $event, mixed $payload = null) passes the payload in one of two ways:
- a value that is not an array is the listener's only argument:
Event::emit('invoice.sent', $invoiceId); - an array is spread into positional arguments, and its keys are ignored.
So an array you want to pass as one argument goes inside a list, as [$order] above. Spreading is useful for several values:
use Taphra\Event;
Event::on('user.signed_up', function (string $email, string $source): void {
echo "{$email} signed up from {$source}\n";
});
Event::emit('user.signed_up', ['[email protected]', 'newsletter']); // prints "[email protected] signed up from newsletter"Emitting ['id' => 42, 'total' => 1990] without the extra list would call the listener with 42 and 1990.
Wildcards and catch-all listeners
#A pattern that ends in .* matches every event name that starts with the part before the *: refund.* matches refund.requested, refund.approved and refund.approved.partial. Only this trailing form is supported.
Event::onAny() registers a listener for every event. It receives the event name first and the payload as given, without spreading:
use Taphra\Event;
$audit = [];
Event::on('refund.*', function (array $refund) use (&$audit): void {
$audit[] = "refund event for order #{$refund['order_id']}";
});
Event::onAny(function (string $event, mixed $payload) use (&$audit): void {
$audit[] = "saw {$event}";
});
Event::emit('refund.requested', [['order_id' => 42]]);
// $audit === ['refund event for order #42', 'saw refund.requested']Order, priorities and errors
#- Listeners registered with the same name or pattern run in the order they were registered.
- Listeners are grouped by the name or pattern they were registered with; the groups run in the order each one got its first listener. If
order.*got its first listener beforeorder.paiddid, theorder.*listeners run first. onAny()listeners run after all the others.- There are no priorities. When the order matters, register the listeners in that order, or have one listener call the next step itself.
- An exception thrown by a listener leaves
emit(): the remaining listeners do not run, and the caller sees the exception.
Removing listeners
#Event::off($event, $listener) removes one listener; it compares by identity, so keep the closure in a variable. Event::off($event) removes every listener of that name or pattern. Event::registered() lists the names and patterns that have listeners.
use Taphra\Event;
$notify = function (array $order): void {
echo "notify\n";
};
Event::on('order.cancelled', $notify);
Event::off('order.cancelled', $notify);
$calledAfterOff = Event::emit('order.cancelled', [['id' => 42]]); // 0Event::flush() removes every listener, the onAny() ones included. It is meant for tests. It also removes the listener the cache registers on its first use (see Events and the cache), so event-driven cache invalidation stops for the rest of that process.
Where to register listeners
#Register listeners once, when the app starts: in app/bootstrap.php, or in the boot() method of a service provider (see container.md). Do not register them inside a controller action. Under FrankenPHP worker mode one PHP process serves many requests: before each request the listener list goes back to what boot registered, so a listener added during a request lasts only for that request.
Events and DataStores
#DataStores do not emit events by themselves. They have their own hooks (beforeSave(), afterSave(), afterDelete() and others) and observers, described in datastores.md. To tell the rest of the app about a change, emit an event from a hook or an observer:
use Taphra\DatabaseConnection;
use Taphra\SchemaBuilder;
(new SchemaBuilder(DatabaseConnection::load('app_master')))->create('orders', function ($t) {
$t->id();
$t->string('customer', 100);
$t->integer('total');
});<?php
// app/DataStores/OrderDataStore.php
namespace App\DataStores;
use Taphra\Event;
class OrderDataStore extends AppDataStore
{
public $objectName = 'orders';
public function afterSave(mixed $data, mixed $result): void
{
Event::emit('order.saved', [$data]);
}
}use App\DataStores\OrderDataStore;
use Taphra\Event;
Event::on('order.saved', function (array $order): void {
echo "New order from {$order['customer']}\n";
});
(new OrderDataStore())->save(['customer' => 'Ada', 'total' => 1990]); // prints "New order from Ada"Events and the cache
#Every Event::emit() also deletes the cache entries that subscribed to that event name, such as a cached query result or a cached page. cache.md shows how an entry subscribes.