borobudur/event-dispatcher

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

Borobudur Event Dispatcher Component

dev-master / 0.1.x-dev 2015-08-21 21:36 UTC

This package is not auto-updated.

Last update: 2017-10-05 03:20:35 UTC


README

Build Status License Code Climate Test Coverage Scrutinizer Code Quality SensioLabsInsight

Borobudur\EventDispatcher is lightweight and simple event dispatching component for PHP 5.4+

Installation

  1. Get Composer
  2. Install Borobudur\EventDispatcher with composer require borobudur/event-dispatcher
  3. Add composer autoload on your main PHP file: require __DIR__.'/vendor/autoload.php';

Example

Example 1 - Basic usage

use Borobudur\EventDispatcher\EventDispatcher;

$dispatcher = new EventDispatcher();
$dispatcher->addListener('foo', function() {
    echo 'foo';
});
$dispatcher->fireEvent('foo');

Example 2 - Stop event propagation

use Borobudur\EventDispatcher\EventDispatcher;

$dispatcher = new EventDispatcher();
$dispatcher->addListener('foo', function(Event $event) {
    echo 'foo 1';
    $event->stopPropagation();
});
$dispatcher->addListener('foo', function() {
    echo 'foo 2'; // never be called
});
$dispatcher->fireEvent('foo');

Example 3 - Subscribe class

use Borobudur\EventDispatcher\Subscriber\SubscriberInterface;
use Borobudur\EventDispatcher\Subscriber\SubscriberTrait;

class Controller implements SubscriberInterface
{
    use SubscriberTrait;
    
    public function __construct()
    {
        $this->addListener('before.index', array($this, 'onBeforeIndex'));
        $this->addListener('after.index', array($this, 'onAfterIndex'));
    }
    
    public function index()
    {
        $this->fireEvent('before.index');
        echo 'Hello world'; // response
        $this->fireEvent('after.index');
    }
    
    public function onBeforeIndex()
    {
        // before index handler
    }
    
    public function onAfterIndex()
    {
        // after index handler
    }
}

Example 4 - Add subscriber

use Borobudur\EventDispatcher\Subscriber\SubscriberInterface;
use Borobudur\EventDispatcher\Subscriber\SubscriberTrait;
use Borobudur\EventDispatcher\EventDispatcher;

class View implements SubscriberInterface
{
    use SubscriberTrait;
    
    private $dispatcher;
    
    public function __construct(EventDispatcher $dispatcher)
    {
        $this->addListener('display', array($this, 'onDisplay'));
        $this->dispatcher = $dispatcher;
        $this->dispatcher->addSubscriber($this);
    }
    
    public function display($content)
    {
        echo $content;
        $this->dispatcher->fireEvent('display');
    }
    
    private function onDisplay()
    {
        // handler
    }
}

$dispatcher = new EventDispatcher();
$dispatcher->addListener('display', function() { echo 'page rendered.'; }, -10); // will execute last

$view = new View($dispatcher);
$view->display();

License

MIT Licensed