Skip to content

gobline/mediator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Mediator component

The Mediator component allows your application components to communicate with each other by dispatching events and listening to them. It implements the mediator behavioral design pattern.

Creating the Dispatcher

use Gobline\Mediator\EventDispatcher;

$dispatcher = new EventDispatcher();

Adding Event Subscribers

use Gobline\Mediator\EventSubscriberInterface;

class FooSubscriber implements EventSubscriberInterface
{
    public function onFooEvent()
    {
        // ... do something
    }

    public function getSubscribedEvents()
    {
        return ['fooEvent' => 'onFooEvent'];
    }
}

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

Adding Event Listeners

Event listeners are similar to event subscribers. The only difference is that an event listener doesn't need to implement the EventSubscriberInterface interface and provide the events it listens to. Instead, you specify the events it listens to outside the class. The equivalent of the sample above using an event listener would be:

class FooListener
{
    public function onFooEvent()
    {
        // ... do something
    }
}

$listener = new FooListener();
$dispatcher->addListener($listener, ['fooEvent' => 'onFooEvent']);

Lazy Listeners

You can add a closure which will lazy load the listener instance. This allows the listener to be instantiated only when an event it listens to is dispatched.

$dispatcher->addListener(
    function() { return new FooListener(); },
    ['fooEvent' => 'onFooEvent']);

Dispatching Events

$dispatcher->dispatch('fooEvent');

Passing event data

$dispatcher->dispatch('fooEvent', ['foo' => 'bar']);

class FooListener
{
    public function onFooEvent(array $data)
    {
        // ... do something with $data['foo']
    }
}

Installation

You can install the Mediator component using the dependency management tool Composer. Run the require command to resolve and download the dependencies:

composer require gobline/mediator

About

Dispatch events and listen to them

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages