使用 PHP 库类,我想将其所有公共(public)函数包装在一个子类中......大致如下:
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
}
}
归根结底,我宁愿不必使用相同的包装器代码覆盖每个父类(super class)方法,如果有一种[有点优雅/干净]的方法可以在一个地方完成这一切。
这可能吗?我怀疑我在这里从事元编程领域,甚至不知道 PHP 是否提供这样的野兽,但我想我会问...
最佳答案
您可以使用 __call
轻松做到这一点magic method和一个不直接从基类继承的通用“代理”类。
这是一个(接近)完整的代理类实现,它包装了您传递给它的任何对象。它将围绕每个方法调用调用一些“之前”和“之后”的代码。
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 类设计为其他代理的基类。子代理类可以实现 before
和 after
方法。
缺点是您的“子类”不再实现 BaseClass
,这意味着如果您使用 type-hinting并希望只将 BaseClass
类型的对象传递给函数,这种方法将失败。
关于PHP:将一个类的所有函数包装在一个子类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9525208/