PHP design pattern: Design Patterns in PHP

Source: Internet
Author: User
Tags learn php

This article is for translating articles

Original address: Design Patterns in PHP
If you intend to learn PHP children's shoes can refer to the author's programming language learning Knowledge system Essentials List

This article mainly discusses in the web development, is accurate, is the PHP development the related design pattern and the application. Experienced developers are sure to be familiar with design patterns, but this article is intended primarily for novice developers. First we need to figure out what the design pattern is, design patterns are not a pattern to interpret, they are not a common data structure like linked lists, or a particular application or framework design. In fact, the design pattern is explained as follows:

Descriptions of communicating objects and classes that is customized to solve a general design problem in a particular CO ntext.

On the other hand, design patterns provide a broad and reusable way to solve the problems we often encounter in our daily programming. Design patterns are not necessarily a class library or a third-party framework, they are more of a thought and widely used in the system. They also represent a pattern or template that can be used to solve problems in several different scenarios. Design patterns can be used to speed up development, and many large ideas or designs are implemented in a simple way. Of course, while design patterns work well in development, it's important to avoid misusing them in inappropriate scenarios.

At present, there are 23 kinds of design patterns, which can be divided into the following three categories according to the use target:

Create pattern: Used to create an object to decouple an object from the implementation.

Schema mode: Used to construct large object structures between different objects.

Behavior patterns: Used to manage algorithms, relationships, and responsibilities between different objects.

Creational Patternssingleton (singleton mode)

Singleton mode is one of the most common patterns that are often used in Web application development to allow an accessible instance to be created at run time for a particular class.

  1. /**
  2. * Singleton Class
  3. */
  4. Final class Product
  5. {
  6. /**
  7. * @var Self
  8. */
  9. private static $instance;
  10. /**
  11. * @var Mixed
  12. */
  13. Public $mix;
  14. /**
  15. * Return Self instance
  16. *
  17. * @return Self
  18. */
  19. public static function getinstance () {
  20. if (! ( Self:: $instance instanceof Self)) {
  21. Self:: $instance = new self ();
  22. }
  23. Return self:: $instance;
  24. }
  25. Private Function __construct () {
  26. }
  27. Private Function __clone () {
  28. }
  29. }
  30. $firstProduct = Product::getinstance ();
  31. $secondProduct = Product::getinstance ();
  32. $firstProduct->mix = ' Test ';
  33. $secondProduct->mix = ' example ';
  34. Print_r ($firstProduct->mix);
  35. Example
  36. Print_r ($secondProduct->mix);
  37. Example
Copy Code

In many cases, it is necessary to create a singleton construct for multiple classes in the system, so that a common abstract parent factory method can be established:

  1. Abstract class Factoryabstract {
  2. protected static $instances = Array ();
  3. public static function getinstance () {
  4. $className = Static::getclassname ();
  5. if (! ( Self:: $instances [$className] instanceof $className)) {
  6. Self:: $instances [$className] = new $className ();
  7. }
  8. Return self:: $instances [$className];
  9. }
  10. public static function RemoveInstance () {
  11. $className = Static::getclassname ();
  12. if (Array_key_exists ($className, Self:: $instances)) {
  13. Unset (self:: $instances [$className]);
  14. }
  15. }
  16. Final protected static function GetClassName () {
  17. return Get_called_class ();
  18. }
  19. protected function __construct () {}
  20. Final protected function __clone () {}
  21. }
  22. Abstract class Factory extends Factoryabstract {
  23. Final public static function getinstance () {
  24. return Parent::getinstance ();
  25. }
  26. Final public static function RemoveInstance () {
  27. Parent::removeinstance ();
  28. }
  29. }
  30. Using
  31. Class Firstproduct extends Factory {
  32. Public $a = [];
  33. }
  34. Class Secondproduct extends Firstproduct {
  35. }
  36. Firstproduct::getinstance ()->a[] = 1;
  37. Secondproduct::getinstance ()->a[] = 2;
  38. Firstproduct::getinstance ()->a[] = 3;
  39. Secondproduct::getinstance ()->a[] = 4;
  40. Print_r (Firstproduct::getinstance ()->a);
  41. Array (1, 3)
  42. Print_r (Secondproduct::getinstance ()->a);
  43. Array (2, 4)
Copy CodeRegistry

The registry mode is not very common, it is not a typical creation mode, just to make use of static methods more convenient access to data.

    1. /**
    2. * Registry Class
    3. */
    4. Class Package {
    5. protected static $data = Array ();
    6. public static function set ($key, $value) {
    7. Self:: $data [$key] = $value;
    8. }
    9. public static function Get ($key) {
    10. Return Isset (self:: $data [$key])? Self:: $data [$key]: null;
    11. }
    12. Final public static function Removeobject ($key) {
    13. if (Array_key_exists ($key, Self:: $data)) {
    14. Unset (self:: $data [$key]);
    15. }
    16. }
    17. }
    18. Package::set (' name ', ' package name ');
    19. Print_r (Package::get (' name '));
    20. Package Name
Copy CodeFactory (Factory mode)

The factory pattern is another very common pattern, as its name implies: it is indeed the production factory of the object instance. In some sense, the factory model provides a common approach that helps us get to the object without having to care about its specific intrinsic implementation.

  1. Interface Factory {
  2. Public function getproduct ();
  3. }
  4. Interface Product {
  5. Public function getName ();
  6. }
  7. Class Firstfactory implements Factory {
  8. Public Function getproduct () {
  9. return new Firstproduct ();
  10. }
  11. }
  12. Class Secondfactory implements Factory {
  13. Public Function getproduct () {
  14. return new Secondproduct ();
  15. }
  16. }
  17. Class Firstproduct implements Product {
  18. Public Function GetName () {
  19. Return ' the first product ';
  20. }
  21. }
  22. Class Secondproduct implements Product {
  23. Public Function GetName () {
  24. Return ' Second product ';
  25. }
  26. }
  27. $factory = new Firstfactory ();
  28. $firstProduct = $factory->getproduct ();
  29. $factory = new Secondfactory ();
  30. $secondProduct = $factory->getproduct ();
  31. Print_r ($firstProduct->getname ());
  32. The first product
  33. Print_r ($secondProduct->getname ());
  34. Second Product
Copy CodeAbstractfactory (abstract Factory mode)

In some cases we need to provide different construction plants based on different selection logic, whereas for multiple plants a unified abstraction plant is required:

  1. Class Config {
  2. public static $factory = 1;
  3. }
  4. Interface Product {
  5. Public function getName ();
  6. }
  7. Abstract class Abstractfactory {
  8. public static function GetFactory () {
  9. Switch (Config:: $factory) {
  10. Case 1:
  11. return new Firstfactory ();
  12. Case 2:
  13. return new Secondfactory ();
  14. }
  15. throw new Exception (' bad config ');
  16. }
  17. Abstract public Function getproduct ();
  18. }
  19. Class Firstfactory extends Abstractfactory {
  20. Public Function getproduct () {
  21. return new Firstproduct ();
  22. }
  23. }
  24. Class Firstproduct implements Product {
  25. Public Function GetName () {
  26. Return ' the product from the first factory ';
  27. }
  28. }
  29. Class Secondfactory extends Abstractfactory {
  30. Public Function getproduct () {
  31. return new Secondproduct ();
  32. }
  33. }
  34. Class Secondproduct implements Product {
  35. Public Function GetName () {
  36. Return ' the product from second factory ';
  37. }
  38. }
  39. $firstProduct = Abstractfactory::getfactory ()->getproduct ();
  40. Config:: $factory = 2;
  41. $secondProduct = Abstractfactory::getfactory ()->getproduct ();
  42. Print_r ($firstProduct->getname ());
  43. The first product from the first factory
  44. Print_r ($secondProduct->getname ());
  45. Second Product from Second factory
Copy CodeObject Pool

An object pool can be used to construct and hold a series of objects and get calls when needed:

  1. Class Product {
  2. protected $id;
  3. Public function __construct ($id) {
  4. $this->id = $id;
  5. }
  6. Public Function getId () {
  7. return $this->id;
  8. }
  9. }
  10. Class Factory {
  11. protected static $products = Array ();
  12. public static function Pushproduct (Product $product) {
  13. Self:: $products [$product->getid ()] = $product;
  14. }
  15. public static function GetProduct ($id) {
  16. Return Isset (self:: $products [$id])? Self:: $products [$id]: null;
  17. }
  18. public static function Removeproduct ($id) {
  19. if (Array_key_exists ($id, Self:: $products)) {
  20. Unset (self:: $products [$id]);
  21. }
  22. }
  23. }
  24. Factory::p ushproduct (New Product (' first '));
  25. Factory::p ushproduct (New Product (' second '));
  26. Print_r (Factory::getproduct (' first ')->getid ());
  27. First
  28. Print_r (Factory::getproduct (' second ')->getid ());
  29. Second
Copy CodeLazy initialization (deferred initialization)

Lazy initialization of a variable is often used, and for a class it is often not known which function is used, and some functions are often used only once.

  1. Interface Product {
  2. Public function getName ();
  3. }
  4. Class Factory {
  5. protected $firstProduct;
  6. protected $secondProduct;
  7. Public Function getfirstproduct () {
  8. if (! $this->firstproduct) {
  9. $this->firstproduct = new Firstproduct ();
  10. }
  11. return $this->firstproduct;
  12. }
  13. Public Function getsecondproduct () {
  14. if (! $this->secondproduct) {
  15. $this->secondproduct = new Secondproduct ();
  16. }
  17. return $this->secondproduct;
  18. }
  19. }
  20. Class Firstproduct implements Product {
  21. Public Function GetName () {
  22. Return ' the first product ';
  23. }
  24. }
  25. Class Secondproduct implements Product {
  26. Public Function GetName () {
  27. Return ' Second product ';
  28. }
  29. }
  30. $factory = new Factory ();
  31. Print_r ($factory->getfirstproduct ()->getname ());
  32. The first product
  33. Print_r ($factory->getsecondproduct ()->getname ());
  34. Second Product
  35. Print_r ($factory->getfirstproduct ()->getname ());
  36. The first product
Copy CodePrototype (prototype mode)

Sometimes, some objects need to be initialized multiple times. And especially if initialization takes a lot of time and resources to pre-initialize and store those objects.

    1. !--? php
    2. interface Product {
    3. }
    4. class Factory {
    5. private $product;
    6. Public Function __construct (Product $product) {
    7. $this->product = $product;
    8. }
    9. public Function getproduct () {
    10. return clone $this->product;
    11. }
    12. }
    13. class Someproduct implements Product {
    14. public $name;
    15. }
    16. $prototypeFactory = new Factory (new Someproduct ());
    17. $firstProduct = $prototypeFactory->getproduct ();
    18. $firstProduct->name = ' the first product ';
    19. $secondProduct = $prototypeFactory->getproduct ();
    20. $secondProduct->name = ' Second product ';
    21. print_r ($firstProduct->name);
    22. //The first product
    23. Print_r ($secondProduct->name);
    24. //Second product
Copy CodeBuilder (constructor)

The constructor pattern is primarily about creating complex objects:

  1. Class Product {
  2. Private $name;
  3. Public Function SetName ($name) {
  4. $this->name = $name;
  5. }
  6. Public Function GetName () {
  7. return $this->name;
  8. }
  9. }
  10. Abstract class Builder {
  11. protected $product;
  12. Final public Function getproduct () {
  13. return $this->product;
  14. }
  15. Public Function buildproduct () {
  16. $this->product = new product ();
  17. }
  18. }
  19. Class Firstbuilder extends Builder {
  20. Public Function buildproduct () {
  21. Parent::buildproduct ();
  22. $this->product->setname (' The product of the first builder ');
  23. }
  24. }
  25. Class Secondbuilder extends Builder {
  26. Public Function buildproduct () {
  27. Parent::buildproduct ();
  28. $this->product->setname (' The product of Second Builder ');
  29. }
  30. }
  31. Class Factory {
  32. Private $builder;
  33. Public function __construct (Builder $builder) {
  34. $this->builder = $builder;
  35. $this->builder->buildproduct ();
  36. }
  37. Public Function getproduct () {
  38. return $this->builder->getproduct ();
  39. }
  40. }
  41. $firstDirector = new Factory (new Firstbuilder ());
  42. $secondDirector = new Factory (new Secondbuilder ());
  43. Print_r ($firstDirector->getproduct ()->getname ());
  44. The product of the first builder
  45. Print_r ($secondDirector->getproduct ()->getname ());
  46. The product of second builder
Copy CodeStructural Patternsdecorator (Adorner mode)

Adorner mode allows us to dynamically add different behavioral actions to an object's invocation, depending on the runtime's different scenarios.

  1. Class Htmltemplate {
  2. Any parent class methods
  3. }
  4. Class Template1 extends Htmltemplate {
  5. protected $_html;
  6. Public Function __construct () {
  7. $this->_html = "

    __text__

    ";
  8. }
  9. Public function set ($html) {
  10. $this->_html = $html;
  11. }
  12. Public function render () {
  13. Echo $this->_html;
  14. }
  15. }
  16. Class Template2 extends Htmltemplate {
  17. protected $_element;
  18. Public function __construct ($s) {
  19. $this->_element = $s;
  20. $this->set ("

    " . $this->_html. "

    ");
  21. }
  22. Public Function __call ($name, $args) {
  23. $this->_element-> $name ($args [0]);
  24. }
  25. }
  26. Class Template3 extends Htmltemplate {
  27. protected $_element;
  28. Public function __construct ($s) {
  29. $this->_element = $s;
  30. $this->set ("". $this->_html. "");
  31. }
  32. Public Function __call ($name, $args) {
  33. $this->_element-> $name ($args [0]);
  34. }
  35. }
Copy CodeAdapter (Adapter mode)

This mode allows the use of different interfaces to refactor a class, allowing calls to be made using different invocation methods:

  1. Class Simplebook {
  2. Private $author;
  3. Private $title;
  4. function __construct ($author _in, $title _in) {
  5. $this->author = $author _in;
  6. $this->title = $title _in;
  7. }
  8. function Getauthor () {
  9. return $this->author;
  10. }
  11. function GetTitle () {
  12. return $this->title;
  13. }
  14. }
  15. Class Bookadapter {
  16. Private $book;
  17. function __construct (Simplebook $book _in) {
  18. $this->book = $book _in;
  19. }
  20. function Getauthorandtitle () {
  21. return $this->book->gettitle (). ' By '. $this->book->getauthor ();
  22. }
  23. }
  24. Usage
  25. $book = new Simplebook ("Gamma, Helm, Johnson, and Vlissides", "Design Patterns");
  26. $bookAdapter = new Bookadapter ($book);
  27. Echo ' Author and Title: '. $bookAdapter->getauthorandtitle ();
  28. function echo $line _in) {
  29. echo $line _in. "
    ";
  30. }
Copy CodeBehavioral Patternsstrategy (Policy mode)

The test pattern is primarily intended to allow the customer class to better use certain algorithms without needing to know their specific implementations.

    1. Interface Outputinterface {
    2. Public function load ();
    3. }
    4. Class Serializedarrayoutput implements Outputinterface {
    5. Public function load () {
    6. Return serialize ($arrayOfData);
    7. }
    8. }
    9. Class Jsonstringoutput implements Outputinterface {
    10. Public function load () {
    11. Return Json_encode ($arrayOfData);
    12. }
    13. }
    14. Class Arrayoutput implements Outputinterface {
    15. Public function load () {
    16. return $arrayOfData;
    17. }
    18. }
Copy CodeObserver (Viewer mode)

An object can be set to be observable, as long as it allows other objects to be registered as observers in some way. Whenever the object being observed changes, a message is sent to the observer.

    1. !--? php
    2. interface Observer {
    3. function onChanged ($sender, $args);
    4. }
    5. interface Observable {
    6. function addobserver ($observer);
    7. }
    8. class CustomerList implements Observable {
    9. private $_observers = Array ();
    10. Public Function Addcustomer ($name) {
    11. foreach ($this->_observers as $obs)
    12. $obs OnChanged ($this, $name);
    13. }
    14. public Function Addobserver ($observer) {
    15. $this->_observers []= $observer;
    16. }
    17. }
    18. class Customerlistlogger implements Observer {
    19. public function Onchan Ged ($sender, $args) {
    20. echo ("' $args ' Customer have been added to the list \ n");
    21. }
    22. }
    23. $ul = new UserList ();
    24. $ul->addobserver (New Customerlistlogger ());
    25. $ul->addcustomer ("Jack");
Copy CodeChain of responsibility (responsibility chain mode)

This pattern has another salutation: Control chain mode. It consists primarily of a series of processors for certain commands, each of which is passed in the processor-formed chain of responsibility, at each junction by the processor to determine if they need to be responded to and handled. Each handler pauses when the processor processes the requests.

  1. Interface Command {
  2. function OnCommand ($name, $args);
  3. }
  4. Class Commandchain {
  5. Private $_commands = Array ();
  6. Public Function AddCommand ($cmd) {
  7. $this->_commands[]= $cmd;
  8. }
  9. Public Function RunCommand ($name, $args) {
  10. foreach ($this->_commands as $cmd) {
  11. if ($cmd->oncommand ($name, $args))
  12. Return
  13. }
  14. }
  15. }
  16. Class Custcommand implements Command {
  17. Public Function OnCommand ($name, $args) {
  18. if ($name! = ' Addcustomer ')
  19. return false;
  20. Echo ("This is Customercommand handling ' Addcustomer ' \ n");
  21. return true;
  22. }
  23. }
  24. Class Mailcommand implements Command {
  25. Public Function OnCommand ($name, $args) {
  26. if ($name! = ' mail ')
  27. return false;
  28. Echo ("This is Mailcommand handling ' mail ' \ n");
  29. return true;
  30. }
  31. }
  32. $CC = new Commandchain ();
  33. $CC->addcommand (New Custcommand ());
  34. $CC->addcommand (New Mailcommand ());
  35. $CC->runcommand (' Addcustomer ', null);
  36. $CC->runcommand (' mail ', null);
Copy Code
Php
  • 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.