PHP code example of ghostwriter / event-dispatcher

1. Go to this page and download the library: Download ghostwriter/event-dispatcher library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ghostwriter / event-dispatcher example snippets


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
$listenerProvider = ListenerProvider::new(); // or new ListenerProvider(Container::getInstance())

// Bind the Listener to the Event
$listenerProvider->bind(ExampleEvent::class, ExampleEventListener::class);

// Create an EventDispatcher
$dispatcher = EventDispatcher::new($listenerProvider); // or new EventDispatcher($listenerProvider)

// Dispatch the Event.
$event = $dispatcher->dispatch(new ExampleEvent());

// Assert the Event is the same as the dispatched Event
assert($event instanceof ExampleEvent);

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
$listenerProvider = ListenerProvider::new(); // or new ListenerProvider(Container::getInstance())

// Subscribe the EventSubscriber
$listenerProvider->subscribe(EventSubscriber::class);

// Create an EventDispatcher
$dispatcher = EventDispatcher::new($listenerProvider); // or new EventDispatcher($listenerProvider)

// Dispatch the Event.
$event = $dispatcher->dispatch(new TestEvent());

// Assert the Event is the same as the dispatched Event
assert($event instanceof TestEvent);