自定义事件

easyswoole中,通过Container容器可实现自定义事件功能

新增App/Event/Event.php文件

  1. <?php
  2. namespace App\Event;
  3. use EasySwoole\Component\Container;
  4. use EasySwoole\Component\Singleton;
  5. class Event extends Container
  6. {
  7. use Singleton;
  8. function set($key, $item)
  9. {
  10. if (is_callable($item)){
  11. return parent::set($key, $item);
  12. }else{
  13. return false;
  14. }
  15. }
  16. function hook($event,...$arg){
  17. $call = $this->get($event);
  18. if (is_callable($call)){
  19. return call_user_func($call,...$arg);
  20. }else{
  21. return null;
  22. }
  23. }
  24. }

在框架的initialize事件中进行注册事件:

  1. public static function initialize()
  2. {
  3. // TODO: Implement initialize() method.
  4. date_default_timezone_set('Asia/Shanghai');
  5. \App\Event\Event::getInstance()->set('test', function () {
  6. echo 'test event';
  7. });
  8. }

在其他任意位置调用:

  1. Event::getInstance()->hook('test');

即可触发事件