andrewdyer / event-dispatcher
A framework-agnostic library for implementing the observer pattern through named events and registered listeners
Requires
- php: ^8.3
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.75
- phpunit/phpunit: ^10.5
README
A framework-agnostic library for implementing the observer pattern through named events and registered listeners.
Introduction
This library lets events be defined as classes and listeners attached to them by name, with the dispatcher notifying every registered listener in the order they were added when an event is triggered. Listeners are kept fully decoupled from the code that raises the event, making it straightforward to extend application behaviour without modifying the originating logic, regardless of the framework in use.
Prerequisites
Installation
composer require andrewdyer/event-dispatcher
Getting Started
1. Define an event
Create a class that implements EventInterface, or extend AbstractEvent. By default, the event name is the short (unqualified) class name, but this can be overridden:
namespace App\Events; use AndrewDyer\EventDispatcher\Events\AbstractEvent; class UserRegistered extends AbstractEvent { public function getName(): string { return 'UserRegistered'; } }
2. Create a listener
Create a class that implements ListenerInterface, or extend AbstractListener:
namespace App\Listeners; use AndrewDyer\EventDispatcher\Events\EventInterface; use AndrewDyer\EventDispatcher\Listeners\AbstractListener; class SendRegistrationEmail extends AbstractListener { public function handle(EventInterface $event): void { // Send welcome email to user... } }
3. Set up the dispatcher
Instantiate EventDispatcher:
use AndrewDyer\EventDispatcher\EventDispatcher; $dispatcher = new EventDispatcher();
Usage
Registering a listener
Attach a listener to a specific event name via addListener():
use App\Listeners\SendRegistrationEmail; $dispatcher->addListener('UserRegistered', new SendRegistrationEmail());
Multiple listeners can be registered against the same event name; they are executed in the order they were added.
Dispatching an event
Trigger an event and notify all of its registered listeners via dispatch():
use App\Events\UserRegistered; $dispatcher->dispatch(new UserRegistered());
License
Licensed under the MIT licence and is free for private or commercial projects.