Home  >  Article  >  php教程  >  Constructor Prototype Pattern 原型模式(PHP示例),prototypepattern

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

WBOY
WBOYOriginal
2016-06-13 08:53:351564browse

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

当一个类大部分都是相同的只有部分是不同的时候,如果需要大量这个类的对象,每次都重复实例化那些相同的部分是开销很大的,而如果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>public</span> <span>function</span><span> getServiceConfig()
    {
        </span><span>return</span> <span>array</span><span>(
            </span>'factories' => <span>array</span><span>(
                </span>'Album\Model\AlbumTable' =>  <span>function</span>(<span>$sm</span><span>) {
                    </span><span>$tableGateway</span> = <span>$sm</span>->get('AlbumTableGateway'<span>);
                    </span><span>$table</span> = <span>new</span> AlbumTable(<span>$tableGateway</span><span>);
                    </span><span>return</span> <span>$table</span><span>;
                }</span>,
                'AlbumTableGateway' => <span>function</span> (<span>$sm</span><span>) {
                    </span><span>$dbAdapter</span> = <span>$sm</span>->get('Zend\Db\Adapter\Adapter'<span>);
                    </span><span>$resultSetPrototype</span> = <span>new</span><span> ResultSet();
                    </span><span>$resultSetPrototype</span>->setArrayObjectPrototype(<span>new</span> Album());<span>//</span><span>这个就是一个不变的原型</span>
                    <span>return</span> <span>new</span> TableGateway('album', <span>$dbAdapter</span>, <span>null</span>, <span>$resultSetPrototype</span>);<span>//</span><span>传入到TableGateWay的构造函数中去</span>
                },<span>
            )</span>,<span>
        );
    }</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>php
</span><span>//</span><span>框架中很常见的adapter类,用来适配各种数据库,封装一些基本数据库连接操作。
//相当于上面代码中的adapter类</span>
<span>class</span><span> DbAdapter {
    </span><span>public</span> <span>function</span> fetchAllFromTable(<span>$table</span><span>) {
        </span><span>return</span> <span>$arrayOfData</span><span>;
    }
}

</span><span>//</span><span>运用prototype pattern的类,注意construct和initialize是分开的
//相当于上面zend 代码里面的ResultSet类</span>
<span>class</span><span> RowGateway {

    </span><span>public</span> <span>function</span> __construct(DbAdapter <span>$dbAdapter</span>, <span>$tableName</span><span>) {
        </span><span>$this</span>->dbAdapter = <span>$dbAdapter</span><span>;
        </span><span>$this</span>->tableName = <span>$tableName</span><span>;
    }

    </span><span>public</span> <span>function</span> initialize(<span>$data</span><span>) {
        </span><span>$this</span>->data = <span>$data</span><span>;
    }

    </span><span>/*</span><span>*
     * Both methods require access to the database adapter
     * to fulfill their duties
     </span><span>*/</span>
    <span>public</span> <span>function</span><span> save() {}
    </span><span>public</span> <span>function</span><span> delete() {}
    </span><span>public</span> <span>function</span><span> refresh() {}

}

</span><span>//</span><span>相当于上面代码中的TableGateway类,关于gateway可以具体去了解一下。</span>
<span>class</span><span> UserRepository {

    </span><span>public</span> <span>function</span> __construct(DbAdapter <span>$dbAdapter</span>, RowGateway <span>$rowGatewayPrototype</span> = <span>null</span><span>) {
        </span><span>$this</span>->dbAdapter = <span>$dbAdapter</span><span>;
        </span><span>$this</span>->rowGatewayPrototype = (<span>$rowGatewayPrototype</span>) ? <span>new</span> RowGateway(<span>$this</span>->dbAdapter, 'user'<span>)
    }

    </span><span>public</span> <span>function</span><span> getUsers() {
        </span><span>$rows</span> = <span>array</span><span>();
        </span><span>foreach</span> (<span>$this</span>->dbAdapter->fetchAllFromTable('user') <span>as</span> <span>$rowData</span><span>) {
            </span><span>$rows</span>[] = <span>$row</span> = <span>clone</span> <span>$this</span>-><span>rowGatewayPrototype;
            </span><span>$row</span>->initialize(<span>$rowData</span><span>);
        }
        </span><span>return</span> <span>$rows</span><span>;
    }

}</span>

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

Dbadapter -- adpater

RowGateWay -- ResultSet

UserRepository - TableGateWay

具体看代码中的注释。

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

下面是运用这个类的代码

<span>class</span> ReadWriteRowGateway <span>extends</span><span> RowGateway {
    </span><span>public</span> <span>function</span> __construct(DbAdapter <span>$readDbAdapter</span>, DbAdapter <span>$writeDbAdapter</span>, <span>$tableName</span><span>) {
        </span><span>$this</span>->readDbAdapter = <span>$readDbAdapter</span><span>;
        parent</span>::__construct(<span>$writeDbAdapter</span>, <span>$tableName</span><span>);
    }

    </span><span>public</span> <span>function</span><span> refresh() {
        </span><span>//</span><span> utilize $this->readDbAdapter instead of $this->dbAdapter in RowGateway base implementation</span>
<span>    }
}


</span><span>//</span><span> usage:</span>
<span>$userRepository</span> = <span>new</span><span> UserRepository(
    </span><span>$dbAdapter</span>,
    <span>new</span> ReadWriteRowGateway(<span>$readDbAdapter</span>, <span>$writeDbAdapter</span>, 'user'<span>)
);
</span><span>$users</span> = <span>$userRepository</span>-><span>getUsers();
</span><span>$user</span> = <span>$users</span>[0]; <span>//</span><span> instance of ReadWriteRowGateway with a specific row of data from the db</span>

 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn