devco / event-emitter
使用 traits 将 NodeJSs EventEmitter 端口移植到 PHP 5.4
v1.0.2
2012-04-10 01:21 UTC
Requires
- php: >=5.4.0
This package is not auto-updated.
Last update: 2024-09-23 14:50:00 UTC
README
这是从 EventEmitter 类直接移植到 PHP 5.4 traits 的实现。
为什么是 PHP 5.4?
由于 EventEmitter 功能的性质,使用简单的扩展看起来不是处理它的正确方法,因为它是一组要添加到现有类中的功能,而不是你的类扩展 EventEmitter 的功能。因此,traits 是实现此类功能的最佳方式,并且这些特性仅适用于 PHP 5.4 及以上版本。
如何使用
<?php // if using directly require_once('EventEmitter.php'); // if using through composer just use the autoload require_once('vendor\.composer\autoload.php'); // test class class Item { use \Nekoo\EventEmitter; public function register($infos) { // do something // fire the event $this->emit('register', $infos); } } // allows you to check if a class uses the event emitter through // $class instanceof \Nekoo\EventEmitterInterface class AnotherItem implements \Nekoo\EventEmitterInterface { use \Nekoo\EventEmitter; } // create an instance of our object $i = new Item(); // register an observer for the register event $i->on('register', function($infos) { echo "Item registered!\n"; var_dump($infos); }); // call the method $i->register(array('key' => 'value'));
API
- setMaxListeners(int)
设置事件允许的最大监听器数量,默认为 10。如果同一个对象上同一个事件添加过多的监听器,将使事件触发速度越来越慢,如果需要,可以增加此限制。
<?php $object->setMaxListeners(20);
- emit(string[, mixed arg1, ...])
触发事件,事件名称之后的所有参数都按原样发送到回调函数。
<?php $object->emit('event', $foo, $bar);
- on(string, callable)
为事件注册回调函数,接受所有形式的回调函数(字符串、数组或闭包)。
<?php $object->on('event', function() { var_dump(func_get_args()); });
- addListener(string, callable)
on() 的别名 - all(callable)
为事件注册回调函数,接受所有形式的回调函数(字符串、数组或闭包)。
<?php $object->all(function($event, $arg1) { var_dump($event, $arg1); });
- once(string, callable)
与 on() 相同,但监听器只调用一次。 - off(string, callable)
删除该事件的监听器。您需要提供完全相同的数组或字符串,或者如果使用闭包,则相同的实例。
<?php $fun = function($arg1) { echo "event: $arg1\n"; }; $object->on('event', $fun); // adds the event $object->off('event', $fun); // remove the event
- removeListener(string, callable)
off() 的别名 - removeAllListeners([string])
从给定事件中删除所有监听器,如果没有提供事件,则从所有事件中删除所有监听器。
<?php $object->removeAllListeners('event'); // only for the 'event' event $object->removeAllListeners(); // for every events on the object
- getListeners(string)
返回包含该事件监听器的数组
<?php foreach ($object->getListeners('event') as $listener) { var_dump($listener); }