borobudur/event-dispatcher
Composer 安装命令:
composer require borobudur/event-dispatcher
包简介
Borobudur Event Dispatcher Component
README 文档
README
Borobudur\EventDispatcher is lightweight and simple event dispatching component for PHP 5.4+
Installation
- Get Composer
- Install Borobudur\EventDispatcher with
composer require borobudur/event-dispatcher - 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
统计信息
- 总下载量: 996
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 0
- 依赖项目数: 3
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2015-08-07