I have several classes with several methods. I would like to execute a function with each method call, without a corresponding call in each method.
Is there a way to automate this? Something like a method listerner?
You can declare all your method private and use the magic __call method like this.
<?php
class MyClass
{
private function doSomething($param1, $param2){ //your previously public method
echo "do ".$param1." ".$param2;
}
private function doSomethingForbidden($param1, $param2){ //your previously public method
echo "doSomethingForbidden";
}
private function verifyPermission($methodName){
return in_array($methodName, [
"doSomething"
]);
}
public function __call($name, $arguments)
{
if($this->verifyPermission($name)){
return call_user_func_array(array($this, $name), $arguments);
}else{
throw new \Exception("You can't do that !");
}
}
}
$nc = new MyClass();
$nc->doSomething("pet", "the dog");
//do pet the dog
$nc->doSomethingForbidden("feed", "the birds");
//Fatal error: Uncaught Exception: You can't do that !
when a method is private or does not exists, PHP will automatically routes the call to a __call method if it exists. From there, you can do what you want (check permission, log things, etc.) and since you are now "inside" your class, you can call your private methods yourself using call_user_func_array with the original arguments.
You can learn more reading the documentation for magic methods https://www.php.net/manual/en/language.oop5.overloading.php#object.call
functioninconstructorof eachclass.