borobudur/event-dispatcher

此包已被废弃,不再维护。没有建议的替代包。

Borobudur 事件分发组件

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 是一个轻量级、简单的 PHP 5.4+ 事件分发组件

安装

  1. 获取 Composer
  2. 使用 composer require borobudur/event-dispatcher 安装 Borobudur\EventDispatcher
  3. 在主 PHP 文件中添加 composer 自动加载:require __DIR__.'/vendor/autoload.php';

示例

示例 1 - 基本用法

use Borobudur\EventDispatcher\EventDispatcher;

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

示例 2 - 停止事件传播

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

示例 3 - 订阅类

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
    }
}

示例 4 - 添加订阅者

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

许可证

MIT 许可证