使用 PHP 库类,我想将其所有公共函数包装在一个子类中......大致如下:
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
}
}
归根结底,如果有一种[有点优雅/干净]的方法可以在一个地方完成这一切,我宁愿不必使用相同的包装器代码重写每个超类方法。
这可能吗?我怀疑我正处于元编程领域,甚至不知道 PHP 是否提供了这样的野兽,但我想我会问......
您可以使用以下命令轻松完成此操作__call http://www.php.net/manual/en/language.oop5.overloading.php#object.call 魔术方法 http://www.php.net/manual/en/language.oop5.magic.php以及一个不直接从基类继承的通用“代理”类。
这是代理类的(接近)完整实现,它包装了您传递给它的任何对象。它将在每个方法调用周围调用一些“之前”和“之后”代码。
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
and after
方法。
缺点是你的“子类”不再实现BaseClass
,这意味着如果您正在使用类型提示 http://www.php.net/manual/en/language.oop5.typehinting.php并且想要要求只有类型的对象BaseClass
被传递到一个函数中,这种方法将会失败。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)