Constructor Prototype pattern prototype mode (PHP example)

Source: Internet
Author: User
Tags php example zend zend framework

When a class is mostly the same and only partially different, if you need a large number of objects of this class, it is expensive to instantiate those same parts each time, but if you create the same parts of the object before cloning, you can save overhead.

One way to implement PHP is to __construct () and initialize functions to handle the initialization of this class separately, construct inside the prototype is the public part, initialize inside is the special part of each object. So we first set up a class not initialize, and then each clone this class again initialize on it.

This http://framework.zend.com/manual/2.0/en/user-guide/database-and-models.html is mentioned in the official Manual of the Zend Framework, but not in detail.

First, the introduction

In the ZF2 model there is a albumtable class, equivalent to an Operation Database action helper class, which uses the Tablegateway.

In order for each initialization albumtable to be the same class, the initialization work is put into the root directory of the module.php file Getserviceconfig (), which is used in Factory mode, and through the callback function, when each servicemanager ($ SM) When an object needs to be instantiated, it is automatically called to create a alumtable. As we can see from the code below, creating a albumtable also requires creating a albumtablegateway in the same way, and this class uses the prototype pattern we want to talk about.

Second, the code detailed

  Public functionGetserviceconfig () {return Array(            ' Factories ' =Array(                ' Album\model\albumtable ' =function($SM) {                    $tableGateway=$SM->get (' Albumtablegateway '); $table=NewAlbumtable ($tableGateway); return $table; }, ' albumtablegateway ' =function($SM) {                    $dbAdapter=$SM->get (' Zend\db\adapter\adapter '); $resultSetPrototype=NewResultSet (); $resultSetPrototype->setarrayobjectprototype (NewAlbum ());//This is a constant prototype.                    return NewTablegateway (' album ',$dbAdapter,NULL,$resultSetPrototype);//into the Tablegateway constructor.},            ),        ); }

Note that it is not tablegateway that uses the prototype model but resultset the class. Whenever Tablegateway invokes a method such as select () or insert (), a resultset is used to represent the result, and the public part of the resultset is clone, and the unique part of the class such as data is initialize.

Three, more code examples

To get a clearer idea of the prototype, let's put aside the big frame of Zend and look at a complete code example. Example from

<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>

This article about prototype pattern part of the first half is actually mixed how to use inheritance in the constructor to improve extensibility, two patterns may not seem very good to understand, we look directly at the final code about prototype pattern part.

<?PHP//the adapter class, which is common in the framework, is used to fit a variety of databases and encapsulate some basic database connection operations. Equivalent to the adapter class in the above codeclassDbadapter { Public functionFetchallfromtable ($table) {        return $arrayOfData; }}//using the prototype pattern class, note that construct and initialize are separate//equivalent to the ResultSet class in the Zend code aboveclassRowgateway { Public function__construct (dbadapter$dbAdapter,$tableName) {        $this->dbadapter =$dbAdapter; $this->tablename =$tableName; }     Public functionInitialize$data) {        $this->data =$data; }    /** * Both methods require access to the database adapter * to fulfill their duties*/     Public functionSave () {} Public functionDelete () {} Public functionrefresh () {}}//equivalent to the Tablegateway class in the code above, the gateway can be specifically understood. classUserrepository { Public function__construct (dbadapter$dbAdapter, Rowgateway$rowGatewayPrototype=NULL) {        $this->dbadapter =$dbAdapter; $this->rowgatewayprototype = ($rowGatewayPrototype) ?NewRowgateway ($this->dbadapter, ' user ')    }     Public functiongetusers () {$rows=Array(); foreach($this->dbadapter->fetchallfromtable (' user ') as $rowData) {            $rows[] =$row=Clone $this-Rowgatewayprototype; $row->initialize ($rowData); }        return $rows; }}

These classes are actually corresponding to the classes in the Zend code above.

Dbadapter--Adpater

Rowgateway--ResultSet

Userrepository-tablegateway

See the comments in the code for details.

Rowgateway here can be clearly seen in the getusers need a lot of instantiation, then the prototype mode is very necessary.

Here's the code that uses this class

classReadwriterowgatewayextendsRowgateway { Public function__construct (dbadapter$readDbAdapter, Dbadapter$writeDbAdapter,$tableName) {        $this->readdbadapter =$readDbAdapter; Parent:: __construct ($writeDbAdapter,$tableName); }     Public functionRefresh () {//utilize $this->readdbadapter instead of $this->dbadapter in Rowgateway base implementation    }}//Usage:$userRepository=NewUserrepository ($dbAdapter,NewReadwriterowgateway ($readDbAdapter,$writeDbAdapter, ' user '));$users=$userRepository-getusers ();$user=$users[0];//instance of Readwriterowgateway with a specific row of data from the DB

Constructor Prototype pattern prototype mode (PHP example)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.