This article describes the implementation of PHP event monitoring and triggering method. Share to everyone for your reference. The specific analysis is as follows:
Have nothing to do, think about how PHP implementation of event monitoring, reference to the jquery event binding ideas, a simple implementation.
Main function:
1. Binding events Support one event binding multiple actions, supporting binding one-time events
2. Trigger Event
3. Cancellation of events
Copy Code code 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, ' once ' => $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 [' Once '] && self::remove ($event, $index);
Call_user_func_array ($callback, $args);
}
}
}
Here are some examples of calls:
Copy Code code as follows:
Increase Listener Walk Events
Event::listen (' Walk ', function () {
echo "I am WALKING...N";
});
Increase the listening walk one-time event
Event::listen (' Walk ', function () {
echo "I am LISTENING...N";
}, True);
Trigger 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 ', ' Deeka '); Output I am Deeka
Event::trigger (' Say ', ' Deeka '); 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 your PHP program design.