charm/event
Composer 安装命令:
composer require charm/event
包简介
A simple event emitter interface and a trait with the methods 'on', 'off' and 'emit'.
README 文档
README
Microscopic event emitter implementation. An interface and a trait that provides the methods:
EventEmitterInterface::on( string $eventName, callable $handler )EventEmitterInterface::off( string $eventName, callable $handler = ? )EventEmitterInterface::emit( string $eventName, object $data, bool $cancelable=true )
To allow "hooks" style functionality, a StaticEventEmitterTrait is provided,
which creates a static method StaticEventEmitterTrait::events(): EventEmitterInterface
method. This way you can listen to events on a class level (instead of on a per-instance
basis).
Events that are being processed via EventEmitterInterface::emit can be cancelled
by setting the property 'cancelled' to a "truthy value".
Complete example
<?php
require("vendor/autoload.php");
class Example implements Charm\Event\EventEmitterInterface {
use Charm\Event\EventEmitterTrait;
const SAMPLE_EVENT = 'Example::SAMPLE_EVENT';
}
$instance = new Example();
// First handler
$instance->on(Example::SOME_EVENT, function($data) {
echo "Got: ".$data->message."\n";
$data->cancelled = true;
});
// Second handler won't run because the first handler set `$data->cancelled` to true
$instance->on(Example::SOME_EVENT, function($data) {
echo "No message for me\n";
});
$instance->emit(Example::SOME_EVENT, $data = (object) [ 'message' => 'OK' ]);
Best Practices
There really aren't many best practices. Use this however you want. I like to declare a constant named by class name and constant name, like in the example.
统计信息
- 总下载量: 75
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 2
- 依赖项目数: 3
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2021-03-29