A-A+

php实现监听事件

2020年05月22日 我爱编程 暂无评论

本文介绍关于在php实现事件监听与触发实例程序代码,如何实现事件监听,参考了jQuery的事件绑定思路,简单的实现了一下。

主要功能:

1.绑定事件 支持一个事件绑定多个动作,支持绑定一次性事件

2.触发事件

3.注销事件

代码如下:

  1. class Event
  2. {
  3.     protected static $listens       = array();
  4.     public static function listen($event$callback$once=false){
  5.         if(!is_callable($callback)) return false;
  6.         self::$listens[$event][]    = array('callback'=>$callback'once'=>$once);
  7.         return true;
  8.     }
  9.     public static function one($event$callback){
  10.         return self::listen($event$callback, true);
  11.     }
  12.     public static function remove($event$index=null){
  13.         if(is_null($index))
  14.             unset(self::$listens[$event]);
  15.         else
  16.             unset(self::$listens[$event][$index]);
  17.     }
  18.     public static function trigger(){
  19.         if(!func_num_args()) return;
  20.         $args                       = func_get_args();
  21.         $event                      = array_shift($args);
  22.         if(!isset(self::$listens[$event])) return false;
  23.         foreach((array) self::$listens[$eventas $index=>$listen){
  24.             $callback               = $listen['callback'];
  25.             $listen['once'] && self::remove($event$index);
  26.             call_user_func_array($callback$args);
  27.         }
  28.     }
  29. }

以下是一些调用的例子:

  1. // 增加监听walk事件 
  2. Event::listen('walk'function(){
  3.     echo "I am walking...n";
  4. });
  5. // 增加监听walk一次性事件 
  6. Event::listen('walk'function(){
  7.     echo "I am listening...n";
  8. }, true);
  9. // 触发walk事件 
  10. Event::trigger('walk');
  11. /* 
  12. I am walking... 
  13. I am listening... 
  14. */
  15. Event::trigger('walk');
  16. /* 
  17. I am walking... 
  18. */
  19. Event::one('say'function($name=''){
  20.     echo "I am {$name}n";
  21. });
  22. Event::trigger('say''deeka'); // 输出 I am deeka 
  23. Event::trigger('say''deeka'); // not run 
  24. class Foo
  25. {
  26.     public function bar(){
  27.         echo "Foo::bar() is calledn";
  28.     }
  29.     public function test(){
  30.         echo "Foo::foo() is called, agrs:".json_encode(func_get_args())."n";
  31.     }
  32. }
  33. $foo    = new Foo;
  34. Event::listen('bar'array($foo'bar'));
  35. Event::trigger('bar');
  36. Event::listen('test'array($foo'test'));
  37. Event::trigger('test', 1, 2, 3);
  38. class Bar
  39. {
  40.     public static function foo(){
  41.         echo "Bar::foo() is calledn";
  42.     }
  43. }
  44. Event::listen('bar1'array('Bar''foo'));
  45. Event::trigger('bar1');
  46. Event::listen('bar2''Bar::foo');
  47. Event::trigger('bar2');
  48. function bar(){
  49.     echo "bar() is calledn";
  50. }
  51. Event::listen('bar3''bar');
  52. Event::trigger('bar3');

给我留言

Copyright © 四季博客 保留所有权利.   Theme  Ality

用户登录