PHP Example Constructor Prototype pattern prototype mode, prototypepattern_php tutorial

Source: Internet
Author: User
Tags php example zend framework

PHP Example Constructor Prototype pattern prototype mode, Prototypepattern


Primary roles in prototype mode

Abstract prototype (Prototype) role: Declaring a clone of its own interface
Specific prototype (concrete Prototype) role: Implement a clone of your own operation

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 Function Getserviceconfig ()  {    return array ('      factories ' = = Array (        ' album\model\ Albumtable ' = function ($SM) {          $tableGateway = $sm->get (' Albumtablegateway ');          $table = new Albumtable ($tableGateway);          return $table;        },        ' albumtablegateway ' = function ($SM) {          $dbAdapter = $sm->get (' Zend\db\adapter\ Adapter ');          $resultSetPrototype = new ResultSet ();          $resultSetPrototype->setarrayobjectprototype (New Album ());//This is a constant prototype          return new Tablegateway (' Album ', $ Dbadapter, NULL, $resultSetPrototype);//passed into the constructor of Tablegateway        },      ),    );  }

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

PHP Constructor Best Practices and the Prototype Pattern

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.

The common adapter class in the <?php//framework is used to fit a variety of databases and encapsulate some basic database connection operations.  Equivalent to the adapter class Dbadapter {public Function fetchallfromtable ($table) {return $arrayOfData in the above code; }}//use prototype pattern class, note that construct and initialize are separate//equivalent to the above Zend code inside ResultSet class class Rowgateway {public Function __    Construct (Dbadapter $dbAdapter, $tableName) {$this->dbadapter = $dbAdapter;  $this->tablename = $tableName;  The Public Function Initialize ($data) {$this->data = $data;   }/** * Both methods require access to the database adapter * to fulfill their duties */Public Function Save () {} Public Function Delete () {} public Function refresh () {}}//is equivalent to the Tablegateway class in the code above, the gateway can be specifically understood. Class Userrepository {public function __construct (dbadapter $dbAdapter, rowgateway $rowGatewayPrototype = null) {$th    Is->dbadapter = $dbAdapter; $this->rowgatewayprototype = ($rowGatewayPrototype)?   New Rowgateway ($this->dbadapter, ' user ')} public Function Getusers () {$rows = array (); foreach ($this->dbadapter->fetchallfromtable (' user ') as $rowData) {$rows [] = $row = Clone $this->rowgatewa      Yprototype;    $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

Class Readwriterowgateway extends Rowgateway {public  function __construct (dbadapter $readDbAdapter, Dbadapter $ Writedbadapter, $tableName) {    $this->readdbadapter = $readDbAdapter;    Parent::__construct ($writeDbAdapter, $tableName);  }  Public Function Refresh () {    //utilize $this->readdbadapter instead of the $this->dbadapter in Rowgateway base imple mentation  }}//usage: $userRepository = new Userrepository (  $dbAdapter,  new Readwriterowgateway ($ Readdbadapter, $writeDbAdapter, ' user '), $users = $userRepository->getusers (); $user = $users [0]; Instance of Readwriterowgateway with a specific row of data from the DB

The above content is small to introduce you to the PHP example constructor Prototype pattern prototype model, I hope you like.

http://www.bkjia.com/PHPjc/1061520.html www.bkjia.com true http://www.bkjia.com/PHPjc/1061520.html techarticle PHP Example Constructor Prototype pattern prototype mode, Prototypepattern primary role abstract prototype (PROTOTYPE) role in prototype mode: Declares a clone of its own interface concrete prototype ...

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