activecollab/eventsdispatcher

派发事件,并提供事件处理器

1.0.0 2019-06-23 19:39 UTC

This package is auto-updated.

Last update: 2024-08-24 07:33:58 UTC


README

Build Status

此包提供简单的事件派发器,具有监听器。关键概念

  1. 事件不是任意的字符串,而是封装所有相关事件数据的实例,
  2. 当你指定一个监听器时,你指定一个你想要监听的事件类(或接口),
  3. 你可以通过指定足够一般的的事件类(或接口)来监听整个事件类,
  4. 监听器是可调用的,事件总是作为第一个(也是唯一一个)参数传递给它。

通用监听器示例

<?php

namespace MyApp;

use ActiveCollab\EventsDispatcher\EventsDispatcher;
use ActiveCollab\EventsDispatcher\Test\Fixtures\LicenseRenewedEvent\LicenseRenewedEventInterface;

$dispatcher = new EventsDispatcher();
$dispatcher->listen(LicenseRenewedEventInterface::class, function (LicenseRenewedEventInterface $event) {
    print "License {$event->getLicenseKey()} has been renewed\n";
});

要指定一个全局监听器,处理所有事件,只需在指定时非常通用即可

<?php

namespace MyApp;

use ActiveCollab\EventsDispatcher\EventsDispatcher;
use ActiveCollab\EventsDispatcher\Events\EventInterface;

$dispatcher = new EventsDispatcher();
$dispatcher->listen(EventInterface::class, function (EventInterface $event) {
    print "Event " . get_class($event) . " handled\n";
});

可以采用类似的方法来处理事件类。而不是使用基类 EventInterface,将监听器注册到类或接口上,该类或接口是所有目标类型事件扩展或实现的。

要触发事件,请使用事件作为第一个(也是唯一一个)参数调用 trigger() 方法

<?php

namespace MyApp;

use ActiveCollab\EventsDispatcher\EventsDispatcher;
use ActiveCollab\EventsDispatcher\Test\Fixtures\LicenseRenewedEvent\LicenseRenewedEvent;

$dispatcher = new EventsDispatcher();
$dispatcher->trigger(new LicenseRenewedEvent(
    '123',
    '2016-12-31',
    '2017-12-31',
    699.0
));