Trying to implement pre/post method code: better to use methods or a parent class?
- by Will
I'm finding it difficult to frame this question so ... I want to execute code both before and after a method runs in PHP. There are, as far as I know, two ways to implement this:
Method One: pre and post methods
class Model
{
function find($id)
{
$this->_precode();
// ... do stuff
$this->post_code();
}
}
Add the calls to _precode() and _postcode() to each method where I need this functionality.
Method Two: __call and method naming
class Model extends PrePost
{
function prepost_find($id)
{
// ... do stuff ...
}
}
class PrePost
{
function __call($method,$param)
{
$method = "prepost_$method";
// .. precode here ..
$result = $this->$method($param);
// .. postcode here ..
}
}
This relies on naming a method in a specific way in the inheriting class. Is there a preferred way of doing this? The call method can be made to only handle its specific cases and even defer to a child class's call if there is one.
I'm not looking for opinions; I'm looking to find out if there are valid reasons to choose one way over another.