spiffy/spiffy-event

此包已被弃用且不再维护。未建议替代包。

Spiffy\Event 是一个轻量级、HHVM 兼容且无依赖的事件库。

1.0.1 2014-07-15 22:05 UTC

This package is not auto-updated.

Last update: 2019-02-20 17:53:57 UTC


README

Build Status Code Coverage Scrutinizer Code Quality

安装

可以使用 composer 安装 Spiffy\Event,它将为您设置自动加载。

composer require spiffy/spiffy-event

此外,您还可以下载或克隆仓库并设置自己的自动加载。

创建事件

use Spiffy\Event\Event;

// Create an event that fires on 'foo'
$event = new Event('foo');

// Creates an event with a target
$event = new Event('foo', 'target');
$event->getTarget(); // 'target'

// Event can have parameters too
$event = new Event('foo', 'target', ['foo' => 'bar']);
$event->getParams()['foo']; // 'bar'

监听事件

use Spiffy\Event\EventManager;

$em = new EventManager();

// Listen with a priority of 1
$em->on('foo', function() { echo 'a'; }, 1);

// Listen with a higher priority
$em->on('foo', function() { echo 'b'; }, 10);

// Event default with priority 0
$em->on('foo', function() { echo 'c'; });
$em->on('foo', function() { echo 'd'; });

// echos 'bacd'

触发事件

use Spiffy\Event\Event;
use Spiffy\Event\EventManager;

$em = new EventManager();
$em->on('foo', function() { echo 'fired'; });

// Simplest form of fire requiring just the type
$em->fire('foo'); // fired

// You can also specify the target and params when using the type
$em->fire('foo', 'target', ['foo' => 'bar']);

// You can also provide your own event.
// This is identical to the fire above.
$event = new Event('foo', 'target', ['foo' => 'bar']);
$em->fire($event);

处理响应

use Spiffy\Event\Event;
use Spiffy\Event\EventManager;

$em = new EventManager();

// Respones are returned as a SplQueue (FIFO).
$em->on('foo', function() { return 'a'; });
$em->on('foo', function() { return 'b'; });

// Outputs 'ab'
foreach ($em->fire('foo') as $response) {
    echo $response;
}

插件

有时您可能希望在单个类中收集多个 on() 调用。Spiffy\Event 提供了一个您可以实现的 Plugin 接口,并将其传递给 plug() 方法,以一次性准备多个事件。插件名称用于表示事件集合通常用于向对象添加附加功能。

use Spiffy\Event\Event;
use Spiffy\Event\Plugin;

class MyPlugin implements Plugin
{
    public function plug(Manager $events)
    {
        $events->on('foo', [$this, 'onFoo']);
    }

    public function onFoo(Event $e)
    {
        echo 'do foo';
    }
}

$em = new EventManager();
$em->attach(new MyPlugin());

// output is 'do foo'
$em->fire('foo');