问题描述
使用PHP库类,我想将它的所有公共函数包装在子类中......类似于:
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.
是这可能吗?我怀疑我在这里进行元编程,甚至不知道PHP是否提供了这样的野兽,但我想问...
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 __call
magic method and a generic "proxy" class which doesn't inherit directly from the base class.
这是一个(近)完整的实现一个代理类,它包装你传递它的任何对象。它将在每个方法调用周围调用一些before和after代码。
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.
class MyProxy {
function __construct($object) {
$this->object = $object;
}
function __call($method, $args) {
// Run before code here
// Invoke original method on our proxied object
call_user_func_array(array($this->object, $method), $args);
// Run after code here
}
}
$base = new BaseClass();
$proxy = new MyProxy($base);
$proxy->doSomething(); // invoke $base->doSomething();
您当然希望添加一些错误处理,例如询问代理对象是否响应到 __ call
中的给定方法,如果没有则引发错误。您甚至可以将Proxy类设计为其他代理的基类。子代理类可以在之前实现,在
方法之后实现。
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 __call
and 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 implement before
and after
methods.
缺点是你的子类不再实现 BaseClass
,这意味着如果你正在使用并且想要求只传递 BaseClass
类型的对象进入一个函数,这种方法将失败。
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 type BaseClass
are passed into a function, this approach will fail.
这篇关于PHP:在子类中包装类的所有函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!