I 'd like to know if there is a way to execute a snippet in PHP each time a method is called inside a class. Similar to the way __construct() works, but it should be called on every method call.
2 Answers
You're probably looking for __call(). It will be invoked whenever a non-accesible method is invoked.
class MyClass {
protected function doStuff() {
echo "doing stuff.";
}
public function __call($methodName, $params) {
echo "In before method.";
return $this->doStuff();
}
}
$class = new MyClass();
$class->doStuff(); // In before method.doing stuff.
3 Comments
Paris
The problem is that I want this function to be called on existing methods
Mike B
You can't intercept a method call if it's already accessible in PHP. There's a lot of design patterns and techniques that make this possible and manageable but it all starts by making the method inaccessible in one way or another. You can get into something like
$myClass->callMethod('methodName', array('args')) but that seems like a very poor solutionParis
Nice. So I'll make me methods inaccessible (I 'll find the best way for that. I have 2-3 different ways in my mind) and I will use call. Nice. Thank you very much :-)
I can suggest you to use aspect-oriented library for your needs. You will be able to create a pointcut for methods (regular expression) and just make an advice (closure) to call before/after or around of each method. You can have a look at my library for this: Go! AOP PHP