This paper introduces three kinds of design patterns commonly used in PHP: single-case design mode, factory design pattern and observer design pattern.

Source: Internet
Author: User
Tags learn php
This article gives you a brief introduction of the three most commonly used design patterns in PHP: Single-instance design patterns, factory design patterns, and observer design patterns. Are some of the personal experience of the summary, I hope that small partners can like

This article is to learn PHP commonly used in three design patterns of notes and summaries, regardless of which language development, almost all use to design patterns, why do we need design patterns? What is the role and significance of the birth of the developer?

Do you believe that iOS developers are familiar with design patterns? such as single-case design patterns, factory design patterns, observer patterns, MVC framework structure design patterns and so on.

Next, let's learn about the three most common design patterns in PHP: A single-case design pattern, a factory design pattern, and an observer design pattern.

Single Case design mode

The so-called Singleton pattern, that is, only one instance of the class exists in the application, and once created, it will always exist in memory!

The single-case design pattern is often applied to database class design, and a single-case mode is used to connect only one database to prevent multiple database connections from being opened.

A singleton class should have the following characteristics:

A singleton class cannot be instantiated directly, but only by the class itself. Therefore, to achieve such a restrictive effect, the constructor must be marked private to prevent the class from being instantiated.

A private static member variable is required to hold the class instance and expose a public static method that can access the instance.

In PHP, in order to prevent others from cloning a singleton class instance, it is often provided with an empty private clone() method.

Example of a singleton pattern:

<?php/*** Singleton of Database*/class database{  //We need a static private variable to store a Database instance .  Privatestatic $instance;   Mark as private to prevent it from being instanced.  Privatefunctionconstruct ()  {    //do nothing.  }   Privatefunctionclone ()   {    //do nothing.  }   Publicstatic functiongetinstance ()   {    if (!) ( Self:: $instanceinstanceofself)) {self      :: $instance = Newself ();    }     Returnself:: $instance;  }} $a =database::getinstance (); $b =database::getinstance (); Truevar_dump ($a = = = $b);

Factory design Pattern

Factory design patterns are often used to create an instance of a class that is specifically instantiated and returned based on different input parameters or application configuration.

For example, assuming that the rectangle and the circle have the same method, we use the API provided by the base class to create an instance, by passing parameters to automatically create instances of the corresponding classes, they have the ability to obtain perimeter and area.

<?php Interfaceinterfaceshape {functiongetarea (); Functiongetcircumference ();}/*** Rectangle */class Rectangle  implementsinterfaceshape{private $width;    Private $height;    Publicfunctionconstruct ($width, $height) {$this->width = $width;  $this->height = $height;  } publicfunctiongetarea () {return $this->width* $this->height;  } publicfunctiongetcircumference () {return 2 * $this->width + 2 * $this->height;   }}/*** Circle */class circle implementsinterfaceshape{Private $radius;  Functionconstruct ($radius) {$this->radius = $radius;  } publicfunctiongetarea () {return m_pi * POW ($this->radius, 2);  } publicfunctiongetcircumference () {return 2 * M_PI * $this->radius; }}/*** shape factory class */class Factoryshape {publicstatic functioncreate () {switch (Func_num_args ()) {Case1:retu      RN newcircle (func_get_arg (0));      Case2:return Newrectangle (func_get_arg (0), Func_get_arg (1));     Default: # code ...   Break }}} $rect =factoryshape::create (5, 5);//Object (Rectangle) #1 (2) {["width": "Rectangle":p rivate]=> Int (5) ["Height": "Rectangle":p rivate]=> int (5)}var_dump ($rect); echo "<br>"; Object (Circle) #2 (1) {["Radius": "Circle":p rivate]=> int (4)} $circle =factoryshape::create (4); Var_dump ($circle) ;

Viewer design Pattern

The Observer pattern is a very common design pattern, which can bring great convenience to the program, improper use, will give Yimeimei a difficult to maintain ideas.

What is the Observer pattern? An object makes itself observable by providing methods that allow another object, the observer, to register itself. When an observable object changes, it sends the message to the registered observer. These observers use this information to perform operations that are independent of observable objects. The result is that objects can talk to each other without knowing why. The Observer pattern is an event system, meaning that this pattern allows a class to observe the state of another class, and when the observed class state changes, the observation class can receive notifications and act accordingly; observer patterns provide you with the ability to avoid tight coupling between components. Look at the example below and you'll see!

&LT;?PHP/* Observer interface */interfaceinterfaceobserver{Functiononlisten ($sender, $args); Functiongetobservername ();}  Observable interface interfaceinterfaceobservable{functionaddobserver ($observer); Functionremoveobserver ($observer _name);}   Observer abstract class AbstractClass Observer implementsinterfaceobserver{protected $observer _name;  Functiongetobservername () {return $this->observer_name; } functiononlisten ($sender, $args) {}}//Observable class AbstractClass Observable implementsinterfaceobservable {protected $   Observers = Array (); Publicfunctionaddobserver ($observer) {if ($observerinstanceofInterfaceObserver) {$this->observers[] = $    Observer      }} publicfunctionremoveobserver ($observer _name) {foreach ($this->observersas $index = = $observer) {        if ($observer->getobservername () = = = $observer _name) {array_splice ($this->observers, $index, 1);      Return }}}}//Simulate a class that can be observed classes a extendsobservable {PublicfunctionaddlistenER ($listener) {foreach ($this->observersas $observer) {$observer->onlisten ($this, $listener);   }}}//simulates an observer class B Extendsobserver {protected $observer _name = ' B ';    Publicfunctiononlisten ($sender, $args) {var_dump ($sender);    echo "<br>";    Var_dump ($args);  echo "<br>";   }}//simulates another observer class C Extendsobserver {protected $observer _name = ' C ';    Publicfunctiononlisten ($sender, $args) {var_dump ($sender);    echo "<br>";    Var_dump ($args);  echo "<br>"; }} $a = new A ();//inject observer $a->addobserver (new B ()); $a->addobserver (New C ()); You can see the observed information $a->addlistener (' D '); removing observer $a->removeobserver (' B '); Printed information://Object (A) #1 (1) {["observers":p rotected]=> Array (2) {[0]=> object (B) #2 (1) {["Observer_name":p rotecte D]=> string (1) "B"} [1]=> object (C) #3 (1) {["Observer_name":p rotected]=> string (1) "C"}}}//string (1) "D"// Object (A) #1 (1) {["observers":p rotected]=> Array (2) {[0]=>Object (B) #2 (1) {["Observer_name":p rotected]=> string (1) "B"} [1]=> object (C) #3 (1) {["Observer_name":p rotected] = = String (1) "C"}}}//string (1) "D"

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