Events
PHP event subscriptions, prefix listeners and dispatch.
Installation
Section titled “Installation”composer config repositories.localzet-events vcs https://github.com/localzet/Eventscomposer require localzet/events:dev-mainIn-process events
Section titled “In-process events”localzet\Events is a synchronous dispatcher in one PHP process. on($name, $listener) returns an ID; off($name, $id) removes it and returns 1 or 0. A trailing * matches a prefix, not an arbitrary glob. Exact and prefix listeners share registration order.
emit($name, $data, $halt = false) passes data and event name to each callback. Normally it returns an array of results: listener exceptions are included as Throwable values and dispatch continues; false stops propagation. Halt mode returns the first non-null result, or null. Use listeners(), list() and has() to inspect registrations.
Register worker listeners at startup rather than on every request: the map is static. Remove temporary subscriptions with off to avoid retaining callbacks and captured data. This is not an inter-process queue or a delivery guarantee across restarts.
Requirements
Section titled “Requirements”- php: >=8.0
Example
Section titled “Example”<?php
declare(strict_types=1);
use localzet\Events;
require __DIR__ . '/vendor/autoload.php';
$audit = Events::on('invoice.*', static fn (array $invoice, string $name): string => 'audit:' . $name);$paid = Events::on('invoice.paid', static fn (array $invoice): string => 'paid:' . $invoice['id']);
try { echo json_encode(Events::emit('invoice.paid', ['id' => 42]), JSON_THROW_ON_ERROR), PHP_EOL;} finally { Events::off('invoice.*', $audit); Events::off('invoice.paid', $paid);}Source · AGPL-3.0