Working with a PHP library class, and I’d like to wrap all of its public functions in a subclass… Something along the lines of:
class BaseClass
{
function do_something()
{
some;
stuff;
}
function do_something_else()
{
other;
stuff;
}
/*
* 20-or-so other functions here!
*/
}
class SubClass extends BaseClass
{
function magicalOverrideEveryone()
{
stuff-to-do-before; // i.e. Display header
call_original_function(); // i.e. Display otherwise-undecorated content
stuff-to-do-after; // i.e. Display footer
}
}
Boiling it down, I’d prefer not to have to override every superclass method with the same wrapper code, if there’s a [somewhat elegant / clean] way to do it all in one place.
Is this possible? I suspect I’m in metaprogramming land here, and don’t even know if PHP offers such a beast, but figured I’d ask…
You could do this easily with the
__callmagic method and a generic “proxy” class which doesn’t inherit directly from the base class.Here is a (near) complete implementation of a proxying class which wraps whatever object you pass it. It will invoke some “before” and “after” code around each method call.
You would of course want to add a bit of error handling, like asking the proxied object if it responds to the given method in
__calland raising an error if it doesn’t. You could even design the Proxy class to be a base-class for other proxies. The child proxy classes could implementbeforeandaftermethods.The downside is that your “child class” no longer implements
BaseClass, meaning if you’re using type-hinting and want to demand that only objects of typeBaseClassare passed into a function, this approach will fail.