Trying to implement pre/post method code: better to use methods or a parent class?
Posted
by
Will
on Programmers
See other posts from Programmers
or by Will
Published on 2012-11-13T18:27:05Z
Indexed on
2012/11/13
23:22 UTC
Read the original article
Hit count: 158
php
|best-pactice
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.
© Programmers or respective owner