Is is possible in PHP to trigger an event whenever a function in a class is called, without adding it to every function in the class?
Example:
<?php
class A {
function xxx() {
//this function will be called everytime I call another function in this class
}
public static function b() {
return 'Hello Stackoverflow!';
}
public static function c() {
//I also want this function to trigger the event!
}
}
echo A::b();
?>
What Is a Triggering Event? A triggering event is a tangible or intangible barrier or occurrence which, once breached or met, causes another event to occur. Triggering events include job loss, retirement, or death, and are typical for many types of contracts.
You can select the Via console trigger operation while creating an event trigger to allow invoking the event trigger on rows manually using the Hasura console. Click on the event trigger you want to run and a modal will pop up with the request and response.
This action can be accomplished through JavaScript event handlers. In addition to JavaScript, jQuery which is equivalent to JavaScript in terms of functionality can also be used to trigger events in a HTML document. In order to work on JavaScript trigger events, it is important to know what is an event.
AFAIK there are no native language constructs for this. If you need it for debugging purposes I would advice you to have deeper look into the xdebug extension especially function traces (awesome! :)
Another idea would be to implement __call()
in your class and wrap all public methods. But this requires to change the code and has other side effects:
(simplified example)
class Test {
protected $listeners;
public function __construct() {
$this->listeners = array();
}
private function a() {
echo 'something';
}
private function b() {
echo 'something else';
}
public function __call($fname, $args) {
call_user_func_array(array($this, $fname), $args);
foreach($this->listeners as $listener) {
$listener->notify('fname was called');
}
}
public function addListener(Listener $listener) {
$this->listeners[]= $listener;
}
}
.
class Listener {
public function notify($message) {
echo $message;
}
}
Example:
$t = new Test();
$l = new Listener();
$t->addListener($l);
$t->a();
This is a classic task for aspect oriented programming (AOP). PHP has no native support for AOP, however, there are some frameworks that make AOP in PHP possible. One of these is the GO! AOP PHP framework. You can also implement AOP using runkit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With