core-framework/dispatcher

This package is abandoned and no longer maintained. No replacement package was suggested.

CoreFramework Event Dispatcher Component

v1.0.0 2017-12-05 18:34 UTC

This package is not auto-updated.

Last update: 2022-09-30 22:31:38 UTC


README

The Dispatcher component provides means by which your applications components can communicate with each other by using the Publish/Subscribe model.

Usage

1. Basic usage:

First create a Dispatcher Instance:

$dispatcher = new Dispatcher();

Then subscribe to events using the following syntax:

$dispatcher->on('eventFoo', function() { echo 'foo';});

The second parameter for the on() method can be callable like a Closure (anonymous functions) or can be instances of Core\Events\ListenerInterface.

An Example of listener Class can be as follows:

class TestEventListener implements ListenerInterface
{
    /**
     * @var EventInterface
     */
    public $calledEvent;
    /**
     * @var string
     */
    public $eventName;
    /**
     * @var DispatcherInterface
     */
    public $dispatcher;

    public function __invoke(EventInterface $event, string $eventName = null, DispatcherInterface $dispatcher = null)
    {
        $this->calledEvent = $event;
        $this->eventName = $eventName;
        $this->dispatcher = $dispatcher;
    }
}

The Listener Class you define must implement the ListenerInterface which mandates the definition of the invoke() method.

2. Event Subscribers:

The Dispatcher class provides for means to add Subscribers that can add their own set of event listeners. You can add Subscribers using the addSubscriber() method as follows:

$subscriber = new Subscriber();
$dispatcher->addSubscriber($subscriber);

The defined Subscriber class must implement the SubscriberInterface.