Provides an Event Dispatcher implementation for PHP.
You can install the package via composer:
composer require ghostwriter/event-dispatcher
You can also star (🌟) this repo to find it easier later.
Registering and dispatching an Event Listener.
use Ghostwriter\EventDispatcher\EventDispatcher;
use Ghostwriter\EventDispatcher\ListenerProvider;
// Create an event class
final class ExampleEvent
{
}
// Create an Event Listener
final class ExampleEventListener
{
public function __invoke(ExampleEvent $event): void
{
// Handle the event, e.g., print the event class name
// echo $event::class;
}
}
// Create a ListenerProvider
$provider = ListenerProvider::new(); // or new ListenerProvider()
// Bind the Listener to the Event
$provider->bind(ExampleEvent::class, ExampleEventListener::class);
// Create an EventDispatcher
$dispatcher = EventDispatcher::new($provider); // or new EventDispatcher($provider)
// Dispatch the Event.
$event = $dispatcher->dispatch(new ExampleEvent());
// Assert the Event is the same as the dispatched Event
assert($event instanceof ExampleEvent);
Registering an Event Subscriber.
use Ghostwriter\EventDispatcher\Interface\ListenerProviderInterface;
use Ghostwriter\EventDispatcher\Interface\SubscriberInterface;
use Override;
final class EventSubscriber implements SubscriberInterface {
/**
* @throws Throwable
*/
#[Override]
public function __invoke(ListenerProviderInterface $provider): void
{
// InvokableListener '::__invoke'
$provider->bind(
TestEvent::class,
TestEventListener::class,
);
}
}
// Create a ListenerProvider
$provider = ListenerProvider::new(); // or new ListenerProvider()
// Subscribe the EventSubscriber
$provider->subscribe(EventSubscriber::class);
// Create an EventDispatcher
$dispatcher = EventDispatcher::new($provider); // or new EventDispatcher($provider)
// Dispatch the Event.
$event = $dispatcher->dispatch(new TestEvent());
// Assert the Event is the same as the dispatched Event
assert($event instanceof TestEvent);
Please see CHANGELOG.md for more information what has changed recently.
If you discover any security related issues, please email nathanael.esayeas@protonmail.com
or create a Security Advisory instead of using the issue tracker.
The BSD-3-Clause. Please see License File for more information.