通过使用php的__call()魔术方法,我们可以轻松编写一个拦截所有方法调用的装饰器对象,并缓存返回值.
有一次我做了这样的事情:
class MethodReturnValueCache {
protected $vals = array();
protected $obj;
function __construct($obj) {
$this->obj = $obj;
}
function __call($meth, $args) {
if (!array_key_exists($meth, $this->vals)) {
$this->vals[$meth] = call_user_func_array(array($this->obj, $meth), $args);
}
return $this->vals[$meth];
}
}
然后
$cachedFoon = new MethodReturnValueCache(new foon);
$cachedFoon->getBarn();