actualwave/events

包含事件、事件调度器类以及IEventDispatcher接口,支持事件处理。

0.0.2 2016-01-05 12:33 UTC

This package is not auto-updated.

Last update: 2024-09-14 18:58:23 UTC


README

##PHP-Events 构建状态 覆盖率状态 依赖状态 最新稳定版本 总下载量 许可证

事件允许轻松设置和使用,以便在应用程序组件之间进行通信。事件可以通知状态变化并传递任何类型的数据。

安装

通过 composer

composer require actualwave/events

用法

要使用事件,您不需要实现任何接口,只需创建 EventDispatcher 并为事件注册一些监听器。

class Broadcaster {
  const EVENT_FIRST = 'eventFirst';
  const EVENT_SECOND = 'eventSecond';
  const EVENT_THIRD = 'eventThird';
  /**
   * @var \aw\events\EventDispatcher
   */
  private $_dispatcher;

  //TODO add dispatcher target test
  public function __construct() {
    $this->_dispatcher = new \aw\events\EventDispatcher();
  }

  public function addHandler(string $eventType, callable $handler) {
    $this->_dispatcher->addEventListener($eventType, $handler);
  }

  public function doFirst() {
    echo 'do first and tell ';
    $this->_dispatcher->dispatchEvent(self::EVENT_FIRST);
  }

  public function doSecond() {
    echo 'do second and tell ';
    $this->_dispatcher->dispatchEvent(new \aw\events\ValueEvent(self::EVENT_SECOND, 'pass some data'));
  }

  public function doThird() {
    echo 'do third and tell ';
    $this->_dispatcher->dispatchEvent(self::EVENT_THIRD);
  }
}

在实例化 EventDispatcher 之后,您可以添加监听器并调度事件。

$target = new Broadcaster();
// register event handlers
$target->addHandler(Broadcaster::EVENT_FIRST, function ($event) {
  echo $event->type . PHP_EOL;
});

function secondHandler($event) {
  echo 'handler was called with data: '.$event->value.PHP_EOL;
}

$target->addHandler(Broadcaster::EVENT_SECOND, 'secondHandler');
$target->addHandler(Broadcaster::EVENT_THIRD, [new class () {
  public function eventHandler($event) {
    echo 'event has target: '.json_encode(isset($event->target)).PHP_EOL;
  }
}, 'eventHandler']);
// broadcast events
$target->doThird(); // do third and tell event has target: true
$target->doSecond(); // do second and tell handler was called with data: pass some data
$target->doFirst(); // do first and tell eventFirst