This article will introduce the code for implementing event listening and triggering instance programs in php. I hope some methods will be helpful to anyone who needs them.
I had nothing to worry about. I thought about how to implement event listening in PHP, and referred to jQuery's event binding idea for a simple implementation.
Main functions:
1. Event binding supports binding one event to multiple actions and one-time event binding.
2. trigger events
3. deregister the event
The Code is as follows: |
Copy code |
Class Event { Protected static $ listens = array ();
Public static function listen ($ event, $ callback, $ once = false ){ If (! Is_callable ($ callback) return false; Self: $ listens [$ event] [] = array ('callback' => $ callback, 'one' => $ once ); Return true; }
Public static function one ($ event, $ callback ){ Return self: listen ($ event, $ callback, true ); }
Public static function remove ($ event, $ index = null ){ If (is_null ($ index )) Unset (self ::$ listens [$ event]); Else Unset (self: $ listens [$ event] [$ index]); }
Public static function trigger (){ If (! Func_num_args () return; $ Args = func_get_args (); $ Event = array_shift ($ args ); If (! Isset (self ::$ listens [$ event]) return false; Foreach (array) self: $ listens [$ event] as $ index => $ listen ){ $ Callback = $ listen ['callback']; $ Listen ['one'] & self: remove ($ event, $ index ); Call_user_func_array ($ callback, $ args ); } } } |
The following are some examples of calls:
The Code is as follows: |
Copy code |
// Adds a listener For A walk event. Event: listen ('Walk ', function (){ Echo "I am walking... n "; }); // Adds a one-time event for listening to a walk. Event: listen ('Walk ', function (){ Echo "I am listening... n "; }, True ); // Trigger the walk event Event: trigger ('Walk '); /* I am walking... I am listening... */ Event: trigger ('Walk '); /* I am walking... */
Event: one ('say', function ($ name = ''){ Echo "I am {$ name} n "; });
Event: trigger ('say', 'demoka '); // output I am deeka Event: trigger ('say', 'Demo'); // not run
Class Foo { Public function bar (){ Echo "Foo: bar () is calledn "; }
Public function test (){ Echo "Foo: foo () is called, agrs:". json_encode (func_get_args (). "n "; } }
$ Foo = new Foo;
Event: listen ('bar', array ($ foo, 'bar ')); Event: trigger ('bar ');
Event: listen ('test', array ($ foo, 'test ')); Event: trigger ('test', 1, 2, 3 );
Class Bar { Public static function foo (){ Echo "Bar: foo () is calledn "; } }
Event: listen ('bar1', array ('bar', 'foo ')); Event: trigger ('bar1 ');
Event: listen ('bar2', 'bar: foo '); Event: trigger ('bar2 ');
Function bar (){ Echo "bar () is calledn "; }
Event: listen ('bar3', 'bar '); Event: trigger ('bar3 '); |