復(fù)制代碼 代碼如下:
// 測試
$v = new VirtualProxy(function(){
echo 'Now, Loading', "/n";
$a = new ArrayObject(range(1,100));
$a->abc = 'a';
// 實(shí)際使用中,這里調(diào)用的是 DataMapper 的 findXXX 方法
// 返回的是領(lǐng)域?qū)ο蠹?
return $a;
});
// 代理對(duì)象直接當(dāng)作原對(duì)象訪問
// 而此時(shí)構(gòu)造方法傳入的 callback 函數(shù)才被調(diào)用
// 從而實(shí)現(xiàn)加載對(duì)象操作的延遲
echo $v->abc . $v->offsetGet(50);
復(fù)制代碼 代碼如下:
/**
* 虛代理,只有在被訪問成員時(shí)才調(diào)用閉包函數(shù)生成目標(biāo)對(duì)象。
*
* @author tonyseek
*
*/
class VirtualProxy
{
private $holder = null;
private $loader = null;
/**
* 虛代理,只有在被訪問成員時(shí)才調(diào)用閉包函數(shù)生成目標(biāo)對(duì)象。
*
* @param Closure $loader 生成被代理對(duì)象的閉包函數(shù)
*/
public function __construct(Closure $loader)
{
$this->loader = $loader;
}
/**
* 代理成員方法的調(diào)用
*
* @param string $method
* @param array $arguments
* @throws BadMethodCallException
* @return mixed
*/
public function __call($method, array $arguments = null)
{
$this->check();
if (!method_exists($this->holder, $method)) {
throw new BadMethodCallException();
}
return call_user_func_array(
array(&$this->holder, $method),
$arguments);
}
/**
* 代理成員屬性的讀取
*
* @param string $property
* @throws ErrorException
* @return mixed
*/
public function __get($property)
{
$this->check();
if (!isset($this->holder->$property)) {
throw new ErrorException();
}
return $this->holder->$property;
}
/**
* 代理成員屬性的賦值
*
* @param string $property
* @param mixed $value
*/
public function __set($property, $value)
{
$this->check();
$this->holder->$property = $value;
}
/**
* 檢查是否已經(jīng)存在被代理對(duì)象,不存在則生成。
*/
private function check()
{
if (null == $this->holder) {
$loader = $this->loader;
$this->holder = $loader();
}
}
}
|
新聞熱點(diǎn)
疑難解答