nekoo / eventemitter
使用 traits 将 NodeJS 的 EventEmitter 端口移植到 PHP 5.4
v1.1.0
2020-05-22 01:49 UTC
Requires
- php: >=5.4.0
This package is auto-updated.
Last update: 2024-09-22 10:39:19 UTC
README
这是使用 PHP 5.4 traits 直接移植自 EventEmitter 类的代码。
为什么是 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); }