在延迟加载中避免条件

Exp*_*lls 7 php conditional coding-style lazy-loading

只是为了澄清,我的意思是:

class foon {
   private $barn = null;

   public function getBarn() {
      if (is_null($this->barn)) {
         $this->barn = getBarnImpl();
      }
      return $this->barn;
   }
}
Run Code Online (Sandbox Code Playgroud)

当你并不总是需要时getBarn,这是特别好的,并且getBarn特别昂贵(例如有一个DB调用).有没有办法避免有条件的?这占用了大量空间,看起来很丑陋,看到条件消失总是很好.还有其他一些范例可以处理这种我看不到的延迟加载吗?

goa*_*oat 2

通过使用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];
   }
}
Run Code Online (Sandbox Code Playgroud)

然后

$cachedFoon = new MethodReturnValueCache(new foon);
$cachedFoon->getBarn();
Run Code Online (Sandbox Code Playgroud)