Executing the connection method in PHP

Given a base class in which I have some logic that must be executed before and after a specific method that takes completely different parameters in its different derived classes. As an example:

abstract class Base{ public function pre(){ print "Runing Base::pre()\n"; } public function pos(){ print "Runing Base::post()\n"; } abstract public function doIt(); } class Cheating extends Base { public function doIt(){ $this->pre(); print "Doing it the cheating way\n"; $this->pos(); } } 

But what I really would like to do looks like this:

 class Alpha extends Base { public function doIt($x, $y){ print "Doing it in Alpha with x=$x, y=$y"; } } class Beta extends Base { public function doIt($z){ print "Doing it in Alpha with z=$z"; } } 

And to have some way to always run the pre and pos methods without changing the doIt method itself.

The obvious way should be uniform across all Base pins, it would look something like this:

 abstract class Base { public function pre(){ print "Runing Base::pre()\n"; } public function pos(){ print "Runing Base::post()\n"; } public function process($a,$b){ $this->pre(); $this->doIt($a,$b); $this->pos(); } abstract public function doIt(); } class Wishful extends Base { public function doIt($a, $b){ print "Doing it the Wishful way with a=$a, b=$b\n"; } } 

The problem is that since we have a different number and type of parameters for each doIt implementation, this does not actually solve the problem.

This sounds like a case for hooks - how to implement this? Or any other worthy way to solve the problem ... I believe that there should be a simpler way that I simply am absent - maybe thinking in circles something is wrong.

Thanks!

+4
source share
3 answers

A call with variable arguments can be made using http://php.net/manual/en/function.call-user-func-array.php . Pass $ this as an object.

Getting arguments is a bit more complicated, but can be done with __call: http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods

0
source

You should look at aspect-oriented programming . A lithium frame filter system uses such a thing. Zend Framework 2 also plans to use AOP.

If you want to intercept a function call at the engine level, you can use intercept from PECL.

Google also reveals an excellent infrastructure from which you could LEARN. Look at his code.

In addition, there is a corresponding SO question here: https://stackoverflow.com/questions/4738282/are-there-any-working-aspect-oriented-php-libraries

+2
source

It looks like you want something like:

 function process() { $this->pre(); $result = call_user_func_array( array( $this, 'doIt' ), func_get_args() ); $this->post(); return $result; } 
0
source

All Articles