Home  >  Article  >  Backend Development  >  PHP Practical Design Patterns: Design Patterns in PHP

PHP Practical Design Patterns: Design Patterns in PHP

WBOY
WBOYOriginal
2016-07-23 08:54:42752browse

This article is a translated article

Original address: Design Patterns in PHP
If you are planning to learn PHP, you can refer to the author’s list of key points in the programming language learning knowledge system

This article mainly discusses related design patterns and their applications in web development, to be precise, in PHP development. Experienced developers will certainly be very familiar with design patterns, but this article is primarily aimed at junior developers. First of all, we need to understand what a design pattern is. Design patterns are not a pattern for explanation. They are not common data structures like linked lists, nor are they some special application or framework design. In fact, design patterns are explained as follows:

descriptions of communicating objects and classes that are customized to solve a general design problem in a particular context.

On the other hand, design patterns provide a widely reusable way to solve problems that we often encounter in daily programming. Design patterns are not necessarily a class library or a third-party framework. They are more of an idea and are widely used in systems. They also appear as a pattern or template that can be used to solve problems in many different scenarios. Design patterns can be used to speed up development and implement many big ideas or designs in a simple way. Of course, although design patterns are very useful in development, you must avoid misuse of them in inappropriate scenarios.

There are currently 23 common design patterns, which can be divided into the following three categories according to different usage goals:

Creation pattern: used to create objects to decouple an object from its implementation.

Architectural pattern: used to construct large object structures between different objects.

Behavioral model: used to manage algorithms, relationships and responsibilities between different objects.

Creative Patterns Singleton (single case mode)

The singleton pattern is one of the most common patterns. In the development of web applications, it is often used to allow the creation of an accessible instance of a specific class at runtime.

  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 construction method for multiple classes in the system, so that a common abstraction can be established Parent factory method:

  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 code
Registry

The registration desk mode is not very common, and it is not a typical creation mode. It is just to use static methods to access data more conveniently.

  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 code
Factory(factory mode )

The factory pattern is another very commonly used pattern, and as its name suggests: it is indeed a production factory for object instances. In some sense, the factory pattern provides a general method to help us obtain objects without caring about their specific internal 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 code
AbstractFactory (Abstract Factory Pattern)

In some cases we need to provide different construction factories based on different selection logic, and for multiple factories a unified abstract factory is needed:

  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 code
Object pool

The object pool can be used to construct and store 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::pushProduct(new Product('first'));
  25. Factory::pushProduct(new Product('second' ));
  26. print_r(Factory::getProduct('first')->getId());
  27. // first
  28. print_r(Factory::getProduct('second')->getId());
  29. / /second
Copy code
Lazy Initialization (lazy initialization)

Lazy initialization of a certain variable is also often used. For a class, it is often not known which of its functions will be used, and some functions are often only needed 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 code
Prototype (prototype mode)

Sometimes, some objects need to be initialized multiple times. Especially if initialization requires a lot of time and resources, pre-initialize and store these objects.

  1. interface Product {
  2. }
  3. class Factory {
  4. private $product;
  5. public function __construct(Product $product) {
  6. $this->product = $product;
  7. }
  8. public function getProduct() {
  9. return clone $this->product;
  10. }
  11. }
  12. class SomeProduct implements Product {
  13. public $name;
  14. }
  15. $prototypeFactory = new Factory(new SomeProduct() );
  16. $firstProduct = $prototypeFactory->getProduct();
  17. $firstProduct->name = 'The first product';
  18. $secondProduct = $prototypeFactory->getProduct();
  19. $secondProduct-> name = 'Second product';
  20. print_r($firstProduct->name);
  21. // The first product
  22. print_r($secondProduct->name);
  23. // Second product
Copy code
Builder(构造者)

构造者模式主要在于创建一些复杂的对象:

  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
复制代码
Structural Patterns Decorator(装饰器模式)

装饰器模式允许我们根据运行时不同的情景动态地为某个对象调用前后添加不同的行为动作。

  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. }
复制代码
Adapter(适配器模式)

这种模式允许使用不同的接口重构某个类,可以允许使用不同的调用方式进行调用:

  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. }
复制代码
Behavioral Patterns Strategy(strategy mode)

The test mode is mainly to allow client classes to better use certain algorithms without knowing their specific implementation.

  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 code
Observer (observer mode)

An object can be made observable by allowing other objects to register as observers in some way. Whenever the observed object changes, a message is sent to the observer.

  1. interface Observer {
  2. function onChanged($sender, $args);
  3. }
  4. interface Observable {
  5. function addObserver($observer);
  6. }
  7. class CustomerList implements Observable {
  8. private $_observers = array();
  9. public function addCustomer($name) {
  10. foreach($this->_observers as $obs)
  11. $obs->onChanged($this, $name);
  12. }
  13. public function addObserver($observer) {
  14. $this->_observers []= $observer;
  15. }
  16. }
  17. class CustomerListLogger implements Observer {
  18. public function onChanged($sender, $args) {
  19. echo( "'$ args' Customer has been added to the list n" );
  20. }
  21. }
  22. $ul = new UserList();
  23. $ul->addObserver( new CustomerListLogger() );
  24. $ul->addCustomer( " Jack" );
Copy code
Chain of responsibility (chain of responsibility model)

This mode has another name: control chain mode. It mainly consists of a series of processors for certain commands. Each query will be passed in the chain of responsibilities formed by the processors. At each intersection, the processor determines whether it needs to respond and process them. Each handler will be paused while a processor is available to handle the request.

  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


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn