【片段】PHP 虛代理實現消極式載入

來源:互聯網
上載者:User

簡介:這是【片段】PHP 虛代理實現消極式載入的詳細頁面,介紹了和php,有關的知識、技巧、經驗,和一些php源碼等。

class='pingjiaF' frameborder='0' src='http://biancheng.dnbcw.info/pingjia.php?id=337757' scrolling='no'>

話說這貨是從 Martin 大神的《公司專屬應用程式架構模式》中學到的,輔助 PHP 動態語言的特性,可以比 Java 輕鬆很多的實現消極式載入——通過一個虛代理預留位置。唯一的缺陷,是只能代理對象,不能代理內建基本類型。

我試水的 PHP 領域模型設計中,也是用這個來實現 DomainObject 的消極式載入。

 1 /**
2 * 虛代理,只有在被訪問成員時才調用閉包函數產生目標對象。
3 *
4 * @author tonyseek
5 *
6 */
7 class VirtualProxy
8 {
9 private $holder = null;
10 private $loader = null;
11
12 /**
13 * 虛代理,只有在被訪問成員時才調用閉包函數產生目標對象。
14 *
15 * @param Closure $loader 產生被代理對象的閉包函數
16 */
17 public function __construct(Closure $loader)
18 {
19 $this->loader = $loader;
20 }
21
22 /**
23 * 代理成員方法的調用
24 *
25 * @param string $method
26 * @param array $arguments
27 * @throws BadMethodCallException
28 * @return mixed
29 */
30 public function __call($method, array $arguments = null)
31 {
32 $this->check();
33
34 if (!method_exists($this->holder, $method)) {
35 throw new BadMethodCallException();
36 }
37
38 return call_user_func_array(
39 array(&$this->holder, $method),
40 $arguments);
41 }
42
43 /**
44 * 代理成員屬性的讀取
45 *
46 * @param string $property
47 * @throws ErrorException
48 * @return mixed
49 */
50 public function __get($property)
51 {
52 $this->check();
53
54 if (!isset($this->holder->$property)) {
55 throw new ErrorException();
56 }
57
58 return $this->holder->$property;
59 }
60
61 /**
62 * 代理成員屬性的賦值
63 *
64 * @param string $property
65 * @param mixed $value
66 */
67 public function __set($property, $value)
68 {
69 $this->check();
70
71 $this->holder->$property = $value;
72 }
73
74 /**
75 * 檢查是否已經存在被代理對象,不存在則產生。
76 */
77 private function check()
78 {
79 if (null == $this->holder) {
80 $loader = $this->loader;
81 $this->holder = $loader();
82 }
83 }
84 }
85
86
87 // 測試
88 $v = new VirtualProxy(function(){
89 echo 'Now, Loading', "\n";
90 $a = new ArrayObject(range(1,100));
91 $a->abc = 'a';
92 // 實際使用中,這裡調用的是 DataMapper 的 findXXX 方法
93 // 返回的是領域對象集合
94 return $a;
95 });
96 // 代理對象直接當作原對象訪問
97 // 而此時構造方法傳入的 callback 函數才被調用
98 // 從而實現載入對象操作的延遲
99 echo $v->abc . $v->offsetGet(50);

愛J2EE關注Java邁克爾傑克遜視頻站JSON線上工具

http://biancheng.dnbcw.info/php/337757.html pageNo:9

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.