gplanchat/php-event-manager

该包最新版本(1.1.0)没有可用的许可信息。

基本事件管理器

1.1.0 2014-06-15 15:59 UTC

This package is auto-updated.

Last update: 2024-08-29 03:15:46 UTC


README

PHP事件管理库。

描述

事件发射管理器让您能够实现基于回调的事件管理,用于实现模块化代码或便于类重用。

基于事件的编程目前已在多种语言中提供原生的支持,并带来了一些新的编写代码的方式。考虑到这种模式应该用于使代码更容易维护,这种模式不应在所有情况下都使用,特别是在其他模式更易于实现的情况下。

要求

  • PHP >= 5.4.0

单元测试

在包根目录下运行以下命令以启动PHPUnit单元测试

$ phpunit --strict --configuration build/phpunit.xml

示例

以下代码示例可能对您有所帮助。更多示例可以在tests/文件夹中的单元测试套件中找到。

使用SharedEventEmitter的基本用法

$eventEmitter = new SharedEventEmitter();

// Registering a callback for the event 'ready'
$eventEmitter->on(['ready'], function(Event $e) {
    // Your event code comes here...
});

// ...

// Calling the event
$eventEmitter->emit(new Event('ready'));

将数据传递到事件中

$eventEmitter = new SharedEventEmitter();

// Registering a callback for the event 'ready'
$eventEmitter->on(['ready'], function(Event $e) {
    // Your event code comes here...
});

// ...

// Calling the event
$eventEmitter->emit(new Event('ready', [
    'my_object' => new stdClass
]));

将数据传递到事件中,并为回调定义优先级

$priority = 100;
$callback = function(Event $e) {
    // Your event code comes here...
};

$eventEmitter = new SharedEventEmitter();

// Registering a callback for the event 'ready'
$eventEmitter->on(['ready'], $callback, $priority);

// ...

// Calling the event
$eventEmitter->emit(new Event('ready', [
    'my_object' => new stdClass
]));

在事件发射过程中传递数据

$eventEmitter = new SharedEventEmitter();

// Registering a callback for the event 'ready'
$eventEmitter->on(['ready'], function(Event $e, $isError, $object) {
    // Your event code comes here...
});

// ...

// Calling the event,
$eventEmitter->emit(new Event('ready'), false, new stdClass);

实现EventEmitterInterface接口以构建自己的事件发射器

您可以为添加事件管理到现有框架实现此事件发射器管理器。

class Application
    extends Foo\Framework\ApplicationAbstract
    implements EventEmitterInterface
{
    use EventEmitterTrait;

    public function bootstrap()
    {
        // Bootstrap the instance...

        // emit the 'bootstrap' event, when your method has finished the basic bootstrapping
        $this->emit(new Event('bootstrap', ['application' => $this]));

        return $this;
    }
}

//...

// Registering a callback for the event 'bootstrap'
$eventEmitter->on(['bootstrap'], function(Event $e) {
    // Your event code comes here...
});

//...

// Your caller code looks like this :
$app = new Application();
$app->bootstrap();