自定义事件
最后更新于:2022-04-02 02:21:21
[TOC]
新增 `App/Event/Event.php` 文件
```
namespace App\Event;
use EasySwoole\Component\Container;
use EasySwoole\Component\Singleton;
class Event extends Container{
use Singleton;
function set($key, $item)
{
if (is_callable($item)){
return parent::set($key, $item);
}else{
return false;
}
}
function hook($event,...$arg){
$call = $this->get($event);
if (is_callable($call)){
return call_user_func($call,...$arg);
}else{
return null;
}
}
}
```
在框架的initialize事件中进行注册事件:
```
\App\Event\Event::getInstance()->set('test', function ($arg,$arg1) {
echo "test event:{$arg},{$arg1}\n";
});
\App\Event\Event::getInstance()->set('test2', function ($arg,$arg1) {
echo "test event:{$arg},{$arg1}\n";
});
//别处调用
\App\Event\Event::getInstance()->hook('test','123','222');
//删除 test2 的hook
\App\Event\Event::getInstance()->delete('test2');
//清空所有 hook
//\App\Event\Event::getInstance()->clear();
\App\Event\Event::getInstance()->hook('test2','abc','def');
```
';