自定義事件
在 EasySwoole
中,可以通過 \EasySwoole\Component\Container
容器實(shí)現(xiàn)自定義事件功能。
使用示例
定義事件容器
新增 App\Event\Event.php
文件,內(nèi)容如下:
<?php
/**
* This file is part of EasySwoole.
*
* @link http://www.fe88.cn
* @document http://www.fe88.cn
* @contact http://www.fe88.cn/Preface/contact.html
* @license https://github.com/easy-swoole/easyswoole/blob/3.x/LICENSE
*/
namespace App\Event;
use EasySwoole\Component\Container;
use EasySwoole\Component\Singleton;
class Event extends Container
{
use Singleton;
public function set($key, $item)
{
if (is_callable($item)) {
return parent::set($key, $item);
} else {
return false;
}
}
public function hook($event, ...$args)
{
$call = $this->get($event);
if (is_callable($call)) {
return call_user_func($call, ...$args);
} else {
return null;
}
}
}
注冊(cè)事件
在框架的 initialize
事件(即項(xiàng)目根目錄的 EasySwooleEvent.php
的 initialize
函數(shù))中進(jìn)行注冊(cè)事件:
<?php
/**
* This file is part of EasySwoole.
*
* @link http://www.fe88.cn
* @document http://www.fe88.cn
* @contact http://www.fe88.cn/Preface/contact.html
* @license https://github.com/easy-swoole/easyswoole/blob/3.x/LICENSE
*/
namespace EasySwoole\EasySwoole;
use EasySwoole\EasySwoole\AbstractInterface\Event;
use EasySwoole\EasySwoole\Swoole\EventRegister;
class EasySwooleEvent implements Event
{
public static function initialize()
{
// 注冊(cè)事件
\App\Event\Event::getInstance()->set('test', function () {
echo 'this is test event!' . PHP_EOL;
});
}
public static function mainServerCreate(EventRegister $register)
{
}
}
觸發(fā)事件
注冊(cè)事件之后,就可以在框架的任意位置觸發(fā)事件來進(jìn)行調(diào)用,調(diào)用形式如下:
<?php
\App\Event\Event::getInstance()->hook('test');
在控制器中觸發(fā)事件進(jìn)行調(diào)用
<?php
/**
* This file is part of EasySwoole.
*
* @link http://www.fe88.cn
* @document http://www.fe88.cn
* @contact http://www.fe88.cn/Preface/contact.html
* @license https://github.com/easy-swoole/easyswoole/blob/3.x/LICENSE
*/
namespace App\HttpController;
use EasySwoole\Http\AbstractInterface\Controller;
class Index extends Controller
{
public function index()
{
// 觸發(fā)事件
\App\Event\Event::getInstance()->hook('test');
}
}
訪問
http://127.0.0.1:9501/
(示例請(qǐng)求地址)就可以看到終端顯示如下結(jié)果:this is test event!
。