PHP example detailed constructor Prototype pattern prototype _php Example

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

Primary role in prototype mode

Abstract prototype (Prototype) role: Declares a clone of its own interface
Specific prototype (concrete Prototype) role: Implementing a clone of its own operation

When a class is mostly the same and only part of it is different, it's expensive to repeat the same parts each time you need a lot of this class, and if you create the same parts of the object before the clone, you can save the overhead.

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

This http://framework.zend.com/manual/2.0/en/user-guide/database-and-models.html is mentioned in the Official Handbook of the Zend Framework, but without detail, let me analyze

First, introduce

In ZF2 's model there is a albumtable class, which is equivalent to a Database action Assistant class, which used the Tablegateway.

In order for each initialization albumtable to be the same class, the initialization work is put into the getserviceconfig () of the module.php file in the root directory, which is used in the Factory mode, and the callback function, when each servicemanager ($ SM) When an object is instantiated, it is automatically invoked to create a alumtable. The following code shows that creating a albumtable also requires creating a albumtablegateway in the same way, and this class uses the prototype pattern we're talking 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
          to New Tablegateway (' Album ', $ Dbadapter, NULL, $resultSetPrototype);//passed into the constructor of the Tablegateway
        },)
    ;
  }

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

Third, more code examples

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

<a href= "PHP" >http://ralphschindler.com/2012/03/09/ Php-constructor-best-practices-and-the-prototype-pattern ">php constructor Best practices and prototype pattern </a>

The first half of the section on prototype pattern is actually mixed with how to use inheritance in the constructor to improve extensibility, and two patterns may not seem very well understood, and we look directly at the final code on the part of prototype patterning.

<?php//frames are common adapter classes that are 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; }///Using prototype pattern classes, note that construct and initialize are separate//equal to the ResultSet class class Rowgateway {Public function __ in the above Zend code
    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 () {}}//equivalent to the Tablegateway class in the above code, the gateway can be specifically understood. Class Userrepository {public function __construct (dbadapter $dbAdapter, rowgateway $rowGatewayPrototype = null) {$
    This->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

Look at the comments in the code.

The Rowgateway can be clearly seen in the getusers need a lot of instantiation, then the prototype model 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 $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 series to introduce the PHP example detailed constructor Prototype pattern prototype mode, I hope you like.

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.