league/event
PSR-14 compatible event dispatcher for PHP. Provides an emitter, listeners and subscribers, plus prioritized, stoppable events. Lightweight, extensible, and framework-agnostic—ideal for decoupling application components and building clean event-driven architectures.
Start by installing the package via Composer:
composer require league/event
Since it implements PSR-14 (psr/event-dispatcher), you’ll use it via an event dispatcher. First, instantiate an Emitter (the package’s main class), then attach listeners and dispatch events:
use League\Event\Emitter;
$emitter = new Emitter();
$emitter->addListener('user.registered', function ($event) {
echo "User {$event->getName()} registered!";
});
$emitter->emit(new UserRegisteredEvent('Alice'));
The simplest first use case is decoupling domain logic—e.g., sending a welcome email when a user registers—by attaching side-effect listeners without hard dependencies.
UserRegisteredEvent, OrderShippedEvent) to represent domain happenings. Keep them immutable and stateful (with getters like getUser()).Emitter as a drop-in replacement for any PSR-14 dispatcher (e.g., Symfony’s or Laravel’s EventDispatcher replacements). Integrate with frameworks by injecting Emitter as the dispatcher implementation.$emitter->addListener('user.registered', $handler, 100); // high priority
$emitter->addListener('user.registered', $logger, -10); // low priority
* in listener names to match multiple events (e.g., user.*), useful for logging or auditing.Emitter::pipe() for cross-cutting concerns.league/event does not support stopPropagation() or cancellation—listeners always run (though exceptions may halt flow). Design around this by using exceptions for truly exceptional cases, not flow control.App\Events\User.Registered) to avoid collisions. Consider naming events in past tense (user.created, not user.create).class UserEvents { const REGISTERED = 'user.registered'; }) to avoid typos.Emitter is easy to mock or spy on in tests. For integration tests, attach a mock listener that captures emitted events to assert side effects occurred.Emitter to add domain-specific behavior (e.g., a TransactionalEmitter that only emits events after a DB transaction commits).How can I help you explore Laravel packages today?