folleah/psr7-event-emitter

PSR-7 事件发射器实现

dev-master 2017-06-13 10:06 UTC

This package is not auto-updated.

Last update: 2024-09-23 17:16:48 UTC


README

更多关于功能的信息

一些示例

  • 安全框架,当用户没有权限时,将防止保存/访问数据。
  • 常见的全页缓存系统
  • 日志包,用于跟踪应用程序内执行的所有操作

示例

use Event\Event;
use Event\EventManager;

$onGreeted = function($var) {
    echo "Hi, {$var}.</br>";
};

$onAsked = function() {
    echo "How are you?</br>";
};

$onGoodbye = function() {
    echo "Bye!</br>";
};

$eventManager = new EventManager;
$event = new Event('acquaintance');

// Listen this event with priority
$eventManager->attach('acquaintance', $onGreeted, 2);
$eventManager->attach('acquaintance', $onAsked, 1);
$eventManager->attach('bye', $onGoodbye);

/**
 * Call created event
 * 
 * output:
 * Hi, Alice.
 * How are you?
 */
$eventManager->trigger($event, null, ['Alice']); // 'Alice' will be passed as argument to the listener callback

/**
 * Create new event and call it
 * 
 * output:
 * Bye!
 */
$newEvent = $eventManager->trigger('bye');

使用 stopPropagation() 方法,您可以停止调用剩余的监听器

事件停止传播示例

$eventManager = new EventManager;

$helloWorld = function() {
    echo "Hello world!";
};

$eventManager->attach('hello.world', $helloWorld);

$event = $eventManager->trigger('hello.world');
$event->stopPropagation();
// It will not work
$event = $eventManager->trigger('hello.world');

许可协议:MIT