首頁 後端開發 php教程 Constructor Prototype Pattern 原型模式(PHP示范)

Constructor Prototype Pattern 原型模式(PHP示范)

Jun 13, 2016 pm 12:25 PM
function public

Constructor Prototype Pattern 原型模式(PHP示例)

当一个类大部分都是相同的只有部分是不同的时候,如果需要大量这个类的对象,每次都重复实例化那些相同的部分是开销很大的,而如果clone之前建立对象的那些相同的部分,就可以节约开销。

针对php的一种实现方式就是__construct()和initialize函数分开分别处理这个类的初始化,construct里面放prototype也就是公共的部分,initialize里面是每个对象特殊的部分。这样我们先建立一个类不initialize,以后每次clone这个类再进行initialize就可以了。

 在zend framework官方手册里面提到了这个http://framework.zend.com/manual/2.0/en/user-guide/database-and-models.html,但是没有细讲,下面我来分析一下

一、引入

  在zf2的model里面有一个albumTable类,相当于一个操作数据库动作的助手类,里面用到了tablegateway。

  为了每次初始化albumtable都是相同的一个类,将初始化工作放到了根目录的module.php文件的getServiceConfig(),其中用到工厂模式,并且通过回调函数,当每次ServiceManager($sm)需要实例化一个对象的时候会自动调用创建一个alumTable。下面代码我们可以看出,创建一个albumTable还需要用相同的方式创建一个AlbumTableGateWay,这个类就用到了我们所要讲的原型模式。

二、代码详解

 <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> getServiceConfig()    {        </span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">array</span><span style="color: #000000;">(            </span>'factories' => <span style="color: #0000ff;">array</span><span style="color: #000000;">(                </span>'Album\Model\AlbumTable' =>  <span style="color: #0000ff;">function</span>(<span style="color: #800080;">$sm</span><span style="color: #000000;">) {                    </span><span style="color: #800080;">$tableGateway</span> = <span style="color: #800080;">$sm</span>->get('AlbumTableGateway'<span style="color: #000000;">);                    </span><span style="color: #800080;">$table</span> = <span style="color: #0000ff;">new</span> AlbumTable(<span style="color: #800080;">$tableGateway</span><span style="color: #000000;">);                    </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$table</span><span style="color: #000000;">;                }</span>,                'AlbumTableGateway' => <span style="color: #0000ff;">function</span> (<span style="color: #800080;">$sm</span><span style="color: #000000;">) {                    </span><span style="color: #800080;">$dbAdapter</span> = <span style="color: #800080;">$sm</span>->get('Zend\Db\Adapter\Adapter'<span style="color: #000000;">);                    </span><span style="color: #800080;">$resultSetPrototype</span> = <span style="color: #0000ff;">new</span><span style="color: #000000;"> ResultSet();                    </span><span style="color: #800080;">$resultSetPrototype</span>->setArrayObjectPrototype(<span style="color: #0000ff;">new</span> Album());<span style="color: #008000;">//</span><span style="color: #008000;">这个就是一个不变的原型</span>                    <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">new</span> TableGateway('album', <span style="color: #800080;">$dbAdapter</span>, <span style="color: #0000ff;">null</span>, <span style="color: #800080;">$resultSetPrototype</span>);<span style="color: #008000;">//</span><span style="color: #008000;">传入到TableGateWay的构造函数中去</span>                },<span style="color: #000000;">            )</span>,<span style="color: #000000;">        );    }</span>
登入後複製

注意并不是TableGateWay运用了原型模式而是ResultSet这个类运用了。每当tablegateway调用select()或者insert()等方法的时候都会建立一个ResultSet用来表示结果,这些ResultSet中公共部分被clone,而独特的部分类如data就会被initialize。

三、更多代码示例

  为了更清晰得了解这个原型,我们先抛开zend这个大框架,看一个完整的代码示例。示例来自

<a href="http://ralphschindler.com/2012/03/09/php-constructor-best-practices-and-the-prototype-pattern">PHP Constructor Best Practices And The Prototype Pattern</a>
登入後複製

这篇文章关于prototype pattern的部分前半部分其实是混杂怎样在构造函数中运用继承来提高扩展性,两个模式看起来可能不太好理解,我们直接看最后的代码关于prototype pattern的部分。

<span style="color: #000000;">php</span><span style="color: #008000;">//</span><span style="color: #008000;">框架中很常见的adapter类,用来适配各种数据库,封装一些基本数据库连接操作。//相当于上面代码中的adapter类</span><span style="color: #0000ff;">class</span><span style="color: #000000;"> DbAdapter {    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> fetchAllFromTable(<span style="color: #800080;">$table</span><span style="color: #000000;">) {        </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$arrayOfData</span><span style="color: #000000;">;    }}</span><span style="color: #008000;">//</span><span style="color: #008000;">运用prototype pattern的类,注意construct和initialize是分开的//相当于上面zend 代码里面的ResultSet类</span><span style="color: #0000ff;">class</span><span style="color: #000000;"> RowGateway {    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> __construct(DbAdapter <span style="color: #800080;">$dbAdapter</span>, <span style="color: #800080;">$tableName</span><span style="color: #000000;">) {        </span><span style="color: #800080;">$this</span>->dbAdapter = <span style="color: #800080;">$dbAdapter</span><span style="color: #000000;">;        </span><span style="color: #800080;">$this</span>->tableName = <span style="color: #800080;">$tableName</span><span style="color: #000000;">;    }    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> initialize(<span style="color: #800080;">$data</span><span style="color: #000000;">) {        </span><span style="color: #800080;">$this</span>->data = <span style="color: #800080;">$data</span><span style="color: #000000;">;    }    </span><span style="color: #008000;">/*</span><span style="color: #008000;">*     * Both methods require access to the database adapter     * to fulfill their duties     </span><span style="color: #008000;">*/</span>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> save() {}    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> delete() {}    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> refresh() {}}</span><span style="color: #008000;">//</span><span style="color: #008000;">相当于上面代码中的TableGateway类,关于gateway可以具体去了解一下。</span><span style="color: #0000ff;">class</span><span style="color: #000000;"> UserRepository {    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> __construct(DbAdapter <span style="color: #800080;">$dbAdapter</span>, RowGateway <span style="color: #800080;">$rowGatewayPrototype</span> = <span style="color: #0000ff;">null</span><span style="color: #000000;">) {        </span><span style="color: #800080;">$this</span>->dbAdapter = <span style="color: #800080;">$dbAdapter</span><span style="color: #000000;">;        </span><span style="color: #800080;">$this</span>->rowGatewayPrototype = (<span style="color: #800080;">$rowGatewayPrototype</span>) ? <span style="color: #0000ff;">new</span> RowGateway(<span style="color: #800080;">$this</span>->dbAdapter, 'user'<span style="color: #000000;">)    }    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> getUsers() {        </span><span style="color: #800080;">$rows</span> = <span style="color: #0000ff;">array</span><span style="color: #000000;">();        </span><span style="color: #0000ff;">foreach</span> (<span style="color: #800080;">$this</span>->dbAdapter->fetchAllFromTable('user') <span style="color: #0000ff;">as</span> <span style="color: #800080;">$rowData</span><span style="color: #000000;">) {            </span><span style="color: #800080;">$rows</span>[] = <span style="color: #800080;">$row</span> = <span style="color: #0000ff;">clone</span> <span style="color: #800080;">$this</span>-><span style="color: #000000;">rowGatewayPrototype;            </span><span style="color: #800080;">$row</span>->initialize(<span style="color: #800080;">$rowData</span><span style="color: #000000;">);        }        </span><span style="color: #0000ff;">return</span> <span style="color: #800080;">$rows</span><span style="color: #000000;">;    }}</span>
登入後複製

这几个类其实和上面zend代码中的类是对应的

Dbadapter -- adpater

RowGateWay -- ResultSet

UserRepository - TableGateWay

具体看代码中的注释。

这里的RowGateWay可以很明显的看出在getusers中需要大量的实例化,那么原型模式就是很必要的了。

下面是运用这个类的代码

<span style="color: #0000ff;">class</span> ReadWriteRowGateway <span style="color: #0000ff;">extends</span><span style="color: #000000;"> RowGateway {    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> __construct(DbAdapter <span style="color: #800080;">$readDbAdapter</span>, DbAdapter <span style="color: #800080;">$writeDbAdapter</span>, <span style="color: #800080;">$tableName</span><span style="color: #000000;">) {        </span><span style="color: #800080;">$this</span>->readDbAdapter = <span style="color: #800080;">$readDbAdapter</span><span style="color: #000000;">;        parent</span>::__construct(<span style="color: #800080;">$writeDbAdapter</span>, <span style="color: #800080;">$tableName</span><span style="color: #000000;">);    }    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> refresh() {        </span><span style="color: #008000;">//</span><span style="color: #008000;"> utilize $this->readDbAdapter instead of $this->dbAdapter in RowGateway base implementation</span><span style="color: #000000;">    }}</span><span style="color: #008000;">//</span><span style="color: #008000;"> usage:</span><span style="color: #800080;">$userRepository</span> = <span style="color: #0000ff;">new</span><span style="color: #000000;"> UserRepository(    </span><span style="color: #800080;">$dbAdapter</span>,    <span style="color: #0000ff;">new</span> ReadWriteRowGateway(<span style="color: #800080;">$readDbAdapter</span>, <span style="color: #800080;">$writeDbAdapter</span>, 'user'<span style="color: #000000;">));</span><span style="color: #800080;">$users</span> = <span style="color: #800080;">$userRepository</span>-><span style="color: #000000;">getUsers();</span><span style="color: #800080;">$user</span> = <span style="color: #800080;">$users</span>[0]; <span style="color: #008000;">//</span><span style="color: #008000;"> instance of ReadWriteRowGateway with a specific row of data from the db</span>
登入後複製

 

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前 By 尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

function是什麼意思 function是什麼意思 Aug 04, 2023 am 10:33 AM

function是什麼意思

iOS的developer版和public版有什麼不同? iOS的developer版和public版有什麼不同? Mar 01, 2024 pm 12:55 PM

iOS的developer版和public版有什麼不同?

MySQL.proc表的作用與功能詳解 MySQL.proc表的作用與功能詳解 Mar 16, 2024 am 09:03 AM

MySQL.proc表的作用與功能詳解

'enumerate()'函數在Python中的用途是什麼? 'enumerate()'函數在Python中的用途是什麼? Sep 01, 2023 am 11:29 AM

'enumerate()'函數在Python中的用途是什麼?

Vue.use函數的用法與作用 Vue.use函數的用法與作用 Jul 24, 2023 pm 06:09 PM

Vue.use函數的用法與作用

在PHP中的file_exists()函數 在PHP中的file_exists()函數 Sep 14, 2023 am 08:29 AM

在PHP中的file_exists()函數

js函數function用法是什麼 js函數function用法是什麼 Oct 07, 2023 am 11:25 AM

js函數function用法是什麼

如何在PHP中使用SOA函數 如何在PHP中使用SOA函數 May 18, 2023 pm 01:10 PM

如何在PHP中使用SOA函數

See all articles