borobudur / event-dispatcher
Borobudur Event Dispatcher Component
Installs: 996
Dependents: 3
Suggesters: 0
Security: 0
Stars: 0
Watchers: 3
Forks: 0
Open Issues: 0
Type:borobudur-component
Requires
- php: >=5.4.0
Requires (Dev)
- codeclimate/php-test-reporter: dev-master
- phpunit/phpunit: ~4.0
This package is not auto-updated.
Last update: 2017-10-05 03:20:35 UTC
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();