PHP中使用虛代理實現(xiàn)延遲加載技術(shù)
話說這貨是從 Martin 大神的《企業(yè)應(yīng)用架構(gòu)模式》中學到的,輔助 PHP 動態(tài)語言的特性,可以比 Java 輕松很多的實現(xiàn)延遲加載——通過一個虛代理占位符。唯一的缺陷,是只能代理對象,不能代理內(nèi)置基本類型。
我試水的 PHP 領(lǐng)域模型設(shè)計中,也是用這個來實現(xiàn) DomainObject 的延遲加載。
* 虛代理,只有在被訪問成員時才調(diào)用閉包函數(shù)生成目標對象。
*
* @author tonyseek
*
*/
class VirtualProxy
{
private $holder = null;
private $loader = null;
/**
* 虛代理,只有在被訪問成員時才調(diào)用閉包函數(shù)生成目標對象。
*
* @param Closure $loader 生成被代理對象的閉包函數(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)存在被代理對象,不存在則生成。
*/
private function check()
{
if (null == $this->holder) {
$loader = $this->loader;
$this->holder = $loader();
}
}
}
// 測試
$v = new VirtualProxy(function(){
echo 'Now, Loading', "\n";
$a = new ArrayObject(range(1,100));
$a->abc = 'a';
// 實際使用中,這里調(diào)用的是 DataMapper 的 findXXX 方法
// 返回的是領(lǐng)域?qū)ο蠹?br />
return $a;
});
// 代理對象直接當作原對象訪問
// 而此時構(gòu)造方法傳入的 callback 函數(shù)才被調(diào)用
// 從而實現(xiàn)加載對象操作的延遲
echo $v->abc . $v->offsetGet(50);
相關(guān)文章
PHP與MongoDB簡介|安全|M+PHP應(yīng)用實例詳解
本篇文章是對PHP中的MongoDB簡介|安全|M+PHP應(yīng)用實例進行了詳細的分析介紹,需要的朋友參考下2013-06-06解析VS2010利用VS.PHP插件調(diào)試PHP的方法
以下是對VS2010利用VS.PHP插件調(diào)試PHP的方法進行了詳細的分析介紹,需要的朋友可以過來參考下2013-07-07PHP之將POST數(shù)據(jù)轉(zhuǎn)化為字符串的實現(xiàn)代碼
今天來分享一個方便我們做LOG日志記錄的自定義函數(shù),需要將POST數(shù)據(jù)轉(zhuǎn)化為字符串,需要的朋友可以參考下2016-11-11