Skip to content

ghostwriter/event-dispatcher

Repository files navigation

Event Dispatcher

Automation Supported PHP Version GitHub Sponsors Mutation Coverage Code Coverage Type Coverage Latest Version on Packagist Downloads

Provides an Event Dispatcher implementation for PHP.

Installation

You can install the package via composer:

composer require ghostwriter/event-dispatcher

Star ⭐️ this repo if you find it useful

You can also star (🌟) this repo to find it easier later.

Usage

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);

Event Subscriber

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);

Changelog

Please see CHANGELOG.md for more information what has changed recently.

Security

If you discover any security related issues, please email [email protected] or create a Security Advisory instead of using the issue tracker.

License

The BSD-3-Clause. Please see License File for more information.