1: <?php
2: 3: 4: 5: 6: 7:
8:
9: namespace GLFramework;
10:
11:
12: use GLFramework\Module\Module;
13:
14: class Events
15: {
16: private static $instance;
17: private $handlers = array();
18:
19: 20: 21:
22: public function __construct()
23: {
24: self::$instance = $this;
25: }
26:
27: 28: 29:
30: public static function getInstance()
31: {
32: return self::$instance;
33: }
34:
35: 36: 37: 38: 39: 40: 41:
42: public function listen($event, $fn, $context = array())
43: {
44: if(!isset($this->handlers[$event]))
45: {
46: $this->handlers[$event] = array();
47: }
48: $this->handlers[$event][] = array('fn' => $fn, 'context' => $context);
49:
50: }
51:
52: 53: 54: 55: 56: 57: 58: 59: 60: 61:
62: public static function fire($event, $args = array())
63: {
64: return self::getInstance()->_fire($event, $args);
65: }
66:
67: public function _fire($event, $args = array())
68: {
69: global $context;
70: $buffer = array();
71: if(!is_array($args)) $args = array($args);
72: if(isset($this->handlers[$event]) && count(($this->handlers[$event])) > 0)
73: {
74: $handlers = $this->handlers[$event];
75: foreach($handlers as $item)
76: {
77: $fn = $item['fn'];
78: $context = $item['context'];
79: if(is_callable($fn))
80: {
81: $result = call_user_func_array($fn, $args);
82: if($result === true)
83: {
84: return true;
85: }
86: else
87: {
88: $buffer[] = $result;
89: }
90: }
91: else
92: {
93: Log::getInstance()->error("Can not call event: " . $event . " function: " . print_r($fn, true), array('events'));
94: }
95: }
96: return $buffer;
97: }
98: return 0;
99: }
100:
101: public static function anyFalse($result)
102: {
103: foreach ($result as $item)
104: if($item === false) return true;
105: return false;
106: }
107:
108: 109: 110:
111: public static function getContext()
112: {
113: global $context;
114: return $context;
115: }
116: }