Userland events in PHP
This here is an extension to allow users to decare and Zend to fire events at runtime, because delicious ...
How ...
The following code demonstrates how to attach events to the invokation of methods or functions:
<?phpclass foo {
publicstaticfunctionbar() {}
/* ... */
}
UEvent::addEvent("foo.bar", ["Foo", "bar"]);
UEvent::addListener("foo.bar", function(array$array = []){
echo"hello foo::bar\n";
});
/* ... */
foo::bar();
?>Will output:
hello foo::bar
A bit more complicated ...
The following code demonstrates how to use UEventInput in combination with UEventArgs to capture
and pass the argument stack from call to listener
<?phpclass foo {
publicstaticfunctionbar($foo) {}
/* ... */
}
/* Will capture arguments at calltime and trigger event based on arguments also stores argument stack for passing to listener ... so ... voodoo ... */class EventArgs implements UEventInput, UEventArgs {
publicfunctionaccept() {
$this->args = func_get_args();
if (count($this->args)) {
return ($this->args[0] == "trigger");
}
}
publicfunctionget() { return$this->args; }
protected$args;
}
$arguments = newEventArgs();
UEvent::addEvent("foo.bar", ["Foo", "bar"], $arguments);
UEvent::addListener("foo.bar", function($argv){
echo"Foo::bar({$argv}) called\n";
}, $arguments);
foo::bar('trigger');
foo::bar('no-trigger');
?>Will output
Foo::bar(trigger) called
Then names of things and what not ...
<?phpinterface UEventInput {
/*** Shall recieve the argument stack at call time* @returns boolean* Note: use func_get_args*/publicfunctionaccept();
}
interface UEventArgs {
/*** Shall return arguments for event listener invocation* @returns array*/publicfunctionget();
}
class UEvent {
/*** Shall call $handler($args->get()) when $name is fired by uevent* @param string name* @param Closure handler* @returns boolean* @throws \RuntimeException*/publicstaticfunctionaddListener($name, Closure$handler, UEventArgs$args = null);
/*** Shall create an event of the given $name:* $name shall be fired when $input->accept() returns true* @param string name* @param callable call* @param UEventInput input* @returns boolean* @throws \RuntimeException*/publicstaticfunctionaddEvent($name, callable$call, UEventInput$input = null);
/*** Shall return the names of all events* @returns array*/publicstaticfunctiongetEvents();
}
?>