PHP Prototype Model case analysis

Source: Internet
Author: User
Tags autoload
This time for you to bring PHP prototype model case resolution, the use of PHP prototype mode of attention to what, the following is the actual case, together to see.

Prototyping mode (Prototype design pattern) is interesting because it uses a cloning technique to replicate instantiated objects. The new object is created by copying the prototype instance. Here, the instance is a concrete class of batch instantiation. The purpose of the prototype design pattern is to reduce the cost of instantiating objects by using clones. Instead of instantiating a new object from a class, you can use a clone of an existing instance.

Clone function

The key to using the prototype design pattern in PHP is to understand how to use built-in functions clone() .

<?phpabstract class cloneobject{public  $name;  public $picture;  Abstract function Clone ();} Class Boy extends cloneobject{public  function construct ()  {    $this->face = "Handsome";    $this->name = "Chenqionghe";  }  Public function display ()  {    echo ' look: '. $this->face;;    echo ' <br/> '. $this->name. ' <br/> ';  }  Public Function Clone () {}} $boy = new boy (); $boy->display (); $cloneBoy = Clone $boy; $cloneBoy->face = "Still handsome "; $cloneBoy->display ();

The operation results are as follows

Look:handsome
Chenqionghe
Look:still Handsome
Chenqionghe

$cloneBoy instances are $boy by cloning a boy's instance, which can access the same properties as $boy, and change them like a direct instance of the boy class.

Note: for cloned instances, the Clone keyword instantiates another instance of the class for that instance (using the Clone keyword allows you to create a copy of the class, and, if possible, automatically calls the object's clone methods, but not the methods of the object directly clone ), about the procedure, One thing to note is that cloning does not start an action in the constructor.

A simple prototype example

We take the study of fruit flies as an example. The goal of the study was to build a prototype Drosophila, and then, once mutated, build the mutant Drosophila

Abstract class interfaces and concrete implementations

Two specific classes of prototypes (Iprototype) were implemented to represent different sexes of Drosophila, including gender variables (gender) and gender and behavior.

iprototype.php

<?phpabstract class iprototype{public  $eyeColor;  public $winBeat;  public $unitEypes;  Abstract function Clone ();}

The differences between the two implementations of Iprototype are gender-aware, gender is identified by constants, one is male and the other is FEMAIL. Males have a $mated Boolean variable that, after mating, this Boolean variable is set to True and the female flies have a $fecundity variable , which contains a numeric value indicating the reproductive capacity of the male fruit fly (spawning number):

maleproto.php

<?phpinclude_once (' iprototype.php '); class Maleproto extends iprototype{  const gender = "MALE";  public $mated;  Public function construct ()  {    $this->eyecolor = "Red";    $this->winbeat = "the";    $this->uniteypes = "760";  }  Public Function Clone () {}}

femaleproto.php

<?phpinclude_once (' iprototype.php '); class Femaleproto extends iprototype{  const gender = "FEMAIL";  public $fecundity;  Public function construct ()  {    $this->eyecolor = "Red";    $this->winbeat = "the";    $this->uniteypes = "760";  }  Public Function Clone () {}}

Customer

In prototype design mode, the Clien class is indeed an indispensable part. The reason for this is that although the subclasses are specifically implemented as templates for instances, the specific work of cloning instances using the same template is done by the client class

client.php

<?phpfunction autoload ($class _name) {include_once $class _name. php ';}  Class client{//For direct instantiation of private $fly 1;  Private $fly 2;  For cloning private $c 1Fly;  Private $c 2Fly;  Private $updatedCloneFly;    Public Function construct () {//instantiation $this->fly1 = new Maleproto ();    $this->fly2 = new Femaleproto ();    Clone $this->c1fly = Clone $this->fly1;    $this->c2fly = Clone $this->fly2;    $this->updatedclonefly = Clone $this->fly2;    Update clone $this->c1fly->mated = "true";    $this->c2fly->fecundity = ' 186 ';    $this->updatedclonefly->eyecolor = "Purple";    $this->updatedclonefly->winbeat = "220";    $this->updatedclonefly->uniteyes = ' 750 ';    $this->updatedclonefly->fecundity = ' 92 ';    Send $this->showfly ($this->c1fly) by type hint method;    $this->showfly ($this->c2fly);  $this->showfly ($this->updatedclonefly); } Private Function Showfly (Iprototype $fly) {echo "Eye color:". $fly->eyecolor. " <br /> "; echo "Wing beats/second:". $fly->winbeat. "    <br/> "; echo "Eye units:". $fly->uniteypes. "    <br/> ";    $genderNow = $fly:: gender; echo "Gender:". $genderNow. "    <br/> "; if ($genderNow = = "FEMAIL") {echo "Number of eggs:". $fly->fecundity. "    

The operation results are as follows

Eye color:red
Wing beats/second:220
Eye units:760
Gender:male
Mated:trueeye color:red
Wing beats/second:220
Eye units:760
Gender:femail
Number of Eggs:186eye Color:purple
Wing beats/second:220
Eye units:760
Gender:femail
Number of eggs:92

The prototype model relies on the customer to use a specific prototype by not reading the cloning process. In this design process, the customer is a participant in cloning, and since cloning is a key element in prototyping, the customer is a basic participant, not just a request class.

Modern Enterprise organization

In the context of creating design patterns, modern enterprise organizations are well suited to prototype implementations. Enterprise organizations are often complex and large hierarchies, like object-oriented programming, to model many common features. Now describe the software engineering company through an example.

The Software engineering company is a typical modern organization. The Engineering Department (Engineering Department) is responsible for creating products, Management Department (Management) to handle the coordination of resources, marketing Department (Marketing) responsible for product sales, promotion and overall marketing.

Encapsulation in the interface

In this prototype implementation, you first add OOP to the interface of the program (an abstract class), which, like all prototype interfaces, contains a clone operation. In addition, it contains some abstract and specific methods for obtaining and setting methods. There is an abstract get method/set method pair, But to be implemented by 3 concrete prototypes for this abstract get method/set method to provide a concrete implementation. Other methods and settings are applied to attributes such as employee name, ID code, and photo. Note that all of these properties are protection properties (protected), So, although there is public visibility into how the methods and settings are made, the properties used in the operation are protected and visible, which provides some degree of encapsulation:

<?phpabstract class iacmeprototype{  protected $name;  protected $id;  protected $employeePic;  protected $department;  Department  abstract Function setdept ($orgCode);  Abstract function getdept ();  Name Public  function SetName ($emName)  {    $this->name = $emName;  }  Public Function GetName ()  {    return $this->name;  }  ID Public  function SetId ($emId)  {    $this->id = $emId;  }  Public Function getId ()  {    return $this->id;  }  Employee Image public  function setpic ($ePic)  {    $this->employeepic = $ePic;  }  Public Function Getpic ()  {    return $this->employeepic;  }  Abstract function Clone ();}

Using these methods of fetching and setting, the values of all properties are set through inherited protection variables. With this design, the extension classes and their instances can be better encapsulated.

Interface implementation

3 Iacmeprototype subclasses must implement the "dept" Abstract Methods and clone() methods. Similarly, each concrete prototype class also contains a constant unit, which provides an assignment that can be identified by an instance (including the cloned object)

First look at the marketing category in the marketing department:

marketing.php

<?phpinclude_once (' iacmeprototype.php '); class Marketing extends iacmeprototype{  const UNIT = "Marketing";  Private $sales = "Sales";  Private $promotion = "promotion";  Private $strategic = "strategic planning";  Public Function setdept ($orgCode)  {    switch ($orgCode)    {case      101:        $this->department = $this- >sales;        break;      Case 102:        $this->department = $this->promotion;        break;      Case 103:        $this->department = $this->strategic;        break;      Default:        $this->department = "Unrecognized marketing department";    }  }  Public Function getdept ()  {    return $this->department;  }  Public Function Clone () {}}

setDept()The implementation of the method uses a parameter. is not directly into the Department of marketing department, the parameter of this method is a digital code, through a switch statement, limit the 3 acceptable cases and the default situation, the other two prototype implementation is similar

management.php

<?phpinclude_once (' iacmeprototype.php '); class Management extends iacmeprototype{  const UNIT = "Management";  Private $research = "the";  Private $plan = "Planning";  Private $operations = "operations";  Public Function setdept ($orgCode)  {    switch ($orgCode)    {case      201:        $this->department = $this- >research;        break;      Case 202:        $this->department = $this->plan;        break;      Case 203:        $this->department = $this->operations;        break;      Default:        $this->department = "Unrecognized management department";    }  }  Public Function getdept ()  {    return $this->department;  }  Public Function Clone () {}}

engineering.php

<?phpinclude_once (' iacmeprototype.php '); class Engineering extends iacmeprototype{  const UNIT = "Engineering";  Private $development = "development";  Private $design = "Design";  Private $sysAd = "System Administration";  Public Function setdept ($orgCode)  {    switch ($orgCode)    {case      301:        $this->department = $this- >development;        break;      Case 302:        $this->department = $this->design;        break;      Case 303:        $this->department = $this->sysad;        break;      Default:        $this->department = "Unrecognized Engineering department";    }  }  Public Function getdept ()  {    return $this->department;  }  Public Function Clone () {}}

These 3 specific prototype implementations have their specific purpose, but they all conform to an interface, create an instance of each prototype implementation, and then clone multiple instances as needed. This cloning work is done by the client class

Customer

The customer's setup is simple: Create an instance of each specific prototype, and then clone each instance by following the list:

Market Sector Examples:
-----Market Sector cloning
-----Market Sector cloning
Managing an instance of a department
Cloning-----Management Department
Engineering Department Example
Cloning-----Engineering Department
Cloning-----Engineering Department

Only these cloned objects will be used in the future. Use the Get methods and settings method to assign information for each specific situation to these cloned objects. The following is the implementation of the client

client.php

<?phpfunction autoload ($class _name) {include_once $class _name. php ';}  Class client{private $market;  Private $manage;  Private $engineer;    Public Function construct () {$this->makeconproto ();    $Tess = Clone $this->market;    $this->setemployee ($Tess, "Tess Smith", 101, ' ts101-1234 ', ' tess.png ');    $this->showemployee ($Tess);    $Jacob = Clone $this->market;    $this->setemployee ($Jacob, "Jacob Jones", 101, ' jj101-2234 ', ' jacob.png ');    $this->showemployee ($Jacob);    $Ricky = Clone $this->manage;    $this->setemployee ($Ricky, "Ricky Rodriguez", 203, ' rr101-5634 ', ' ricky.png ');    $this->showemployee ($Ricky);    $Olivaia = Clone $this->engineer;    $this->setemployee ($Olivaia, "Olivaia Perez", 302, ' op301-1278 ', ' olivia.png ');    $this->showemployee ($Olivaia);    $John = Clone $this->engineer;    $this->setemployee ($John, "John Jacson", 101, ' jj301-14548 ', ' john.png ');  $this->showemployee ($John); } Private FunctionMakeconproto () {$this->market = new Marketing ();    $this->manage = new Management ();  $this->engineer = new Engineering ();    } Private Function Showemployee (Iacmeprototype $employeeNow) {$px = $employeeNow->getpic ();    echo "<br/> '; echo $employeeNow->getname (). '    <br/> '; echo $employeeNow->getdept (). ': ' $employeeNow:: UNIT. '    <br/> '; echo $employeeNow->getid (). '  

Explain:

The client client's constructor class contains 3 private properties, which are used to instantiate 3 concrete prototype classes respectively. makeConPro()method to generate the necessary instances.

Next, use the cloning technology to create an "employee" instance. This instance sends a specific instance information to a Setup method Setemployee (), which uses the Iacmeprototype interface type hint, but it needs to be explained that it only uses type hints for the first parameter. Other parameters do not have type hints, and they are not required to derive from the Iacmeprototype interface. Cloning an employee can use all the setup methods of the Iacmeprototype abstract class and the Setdept () method implemented by the concrete prototype class.

To use data from individual employees, the client class can use inherited fetch methods. The following is the result of running the client output

Tess Smith
Sales:marketing
ts101-1234
Jacob Jones
Sales:marketing
jj101-2234
Ricky Rodriguez
Operations:management
rr101-5634
Olivaia Perez
Design:engineering
op301-1278
John Jacson
Unidentified Engineering Department: Engineering
jj301-14548

More clones can be added as needed, and only one instantiation of the specific prototype class is required. When using prototype mode, you do not create multiple instances of a specific class, only one class instantiation and multiple clones.

Complete changes, add features

Keep in mind that the most important (and perhaps most basic) design pattern allows developers to modify and patch programs without having to start from scratch. For example, suppose the President decides that it will be difficult to add a new department, such as research, to the company? It's not hard at all. Research can extend Iacmeprototype abstract classes, and then implement abstract acquisition methods and set methods to reflect the organization of this department. It is necessary to note that the code hints used by the client class to get methods and set methods indicate an interface rather than a concrete implementation of an abstract class. So , as long as the added unit correctly implements this interface, it can be successfully added to the application without causing fluctuations or refactoring to other participants in the program.

Not only can you add more specific classes, but you can also easily modify the classes without damaging them. For example, suppose the marketing department of the Organization decided that, in addition to the existing department, they would need a special online marketing department. In this way, the switch/case operation requires a new branch (case) and a new private attribute (variable) to describe the new unit. This change will be frozen in a separate class without affecting the other participants. Since this change does not cause damage, the larger the application size, The more important this is. You can see that the prototype design pattern supports not only consistency, but also flexible changes.

Prototypes in the PHP world

Because PHP is a server-side language and an important tool for interacting with MySQL databases, prototype design patterns are particularly useful. Instead of creating an object for the first element of the database, PHP can use the prototype schema to create an instance of a concrete class and then clone the remaining instances using the data in the database ( Record).

After you understand the cloning process, you might ask, "What's the difference between this and the process of direct instantiation?" In other words, why are clones less resource-specific than directly instantiating objects? Their differences are not directly visible to them. When an object creates an instance from a clone, it does not start the constructor. Clones can get all the properties of the original class, and even the properties of the parent interface. It also inherits all the values that pass the instantiated object. All the values generated by the constructor and the values stored in the object's properties become part of the cloned object. Therefore, the constructor is not returned. If you find that your cloned object does need access to the values generated by the constructor but is inaccessible, this indicates that the class needs to be refactored. Enables instances to have all the information they need, and can pass that data to the cloned object.

In general, prototype patterns are useful in many different types of PHP projects, and you can use prototype mode if you need to solve a problem or even create a pattern.

Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!

Recommended reading:

PHP closure principle (OCP) Use case analysis

PHP dependency Inversion Case detailed

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.