This article mainly introduces how to implement event listening and triggering in php. it can bind time, trigger and deregister functions, and has some reference value, for more information about how to implement event listening and triggering in php, see the example in this article. Share it with you for your reference. The specific analysis is as follows:
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:
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:
// 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 ');
I hope this article will help you with PHP programming.