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.
- /**
- * Singleton class
- */
- final class Product
- {
- /**
- * @var self
- */
- private static $instance;
- /**
- * @var mixed
- */
- public $mix;
- /**
- * Return self instance
- *
- * @return self
- */
- public static function getInstance() {
- if (!(self::$instance instanceof self)) {
- self::$instance = new self() ;
- }
- return self::$instance;
- }
- private function __construct() {
- }
- private function __clone() {
- }
- }
- $firstProduct = Product::getInstance();
- $secondProduct = Product::getInstance();
- $firstProduct->mix = 'test';
- $secondProduct->mix = 'example';
-
- print_r($firstProduct->mix);
- // example
- print_r($secondProduct->mix);
- // 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:
- abstract class FactoryAbstract {
- protected static $instances = array();
- public static function getInstance() {
- $className = static::getClassName();
- if (!(self::$instances[$className] instanceof $className)) {
- self::$instances[$className] = new $className();
- }
- return self::$instances[$className] ;
- }
- public static function removeInstance() {
- $className = static::getClassName();
- if (array_key_exists($className, self::$instances)) {
- unset(self::$instances[$className ]);
- }
- }
- final protected static function getClassName() {
- return get_called_class();
- }
- protected function __construct() { }
- final protected function __clone() { }
- }
- abstract class Factory extends FactoryAbstract {
- final public static function getInstance() {
- return parent::getInstance();
- }
- final public static function removeInstance() {
- parent::removeInstance();
- }
- }
- // using:
- class FirstProduct extends Factory {
- public $a = [];
- }
- class SecondProduct extends FirstProduct {
- }
- FirstProduct::getInstance()->a[] = 1;
- SecondProduct::getInstance( )->a[] = 2;
- FirstProduct::getInstance()->a[] = 3;
- SecondProduct::getInstance()->a[] = 4;
-
- print_r(FirstProduct::getInstance ()->a);
- // array(1, 3)
- print_r(SecondProduct::getInstance()->a);
- // 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.
- /**
- * Registry class
- */
- class Package {
- protected static $data = array();
- public static function set($key, $value) {
- self: :$data[$key] = $value;
- }
- public static function get($key) {
- return isset(self::$data[$key]) ? self::$data[$key] : null ;
- }
- final public static function removeObject($key) {
- if (array_key_exists($key, self::$data)) {
- unset(self::$data[$key]);
- }
- }
- }
- Package::set('name', 'Package name');
- print_r(Package::get('name'));
- //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. - interface Factory {
- public function getProduct();
- }
- interface Product {
- public function getName();
- }
- class FirstFactory implements Factory {
- public function getProduct( ) {
- return new FirstProduct();
- }
- }
- class SecondFactory implements Factory {
- public function getProduct() {
- return new SecondProduct();
- }
- }
- class FirstProduct implements Product {
- public function getName() {
- return 'The first product';
- }
- }
- class SecondProduct implements Product {
- public function getName() {
- return 'Second product';
- }
- }
- $factory = new FirstFactory( );
- $firstProduct = $factory->getProduct();
- $factory = new SecondFactory();
- $secondProduct = $factory->getProduct();
-
- print_r($firstProduct->getName()) ;
- // The first product
- print_r($secondProduct->getName());
- // 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:
- class Config {
- public static $factory = 1;
- }
- interface Product {
- public function getName();
- }
- abstract class AbstractFactory {
- public static function getFactory() {
- switch (Config::$factory) {
- case 1:
- return new FirstFactory();
- case 2:
- return new SecondFactory();
- }
- throw new Exception('Bad config');
- }
- abstract public function getProduct();
- }
- class FirstFactory extends AbstractFactory {
- public function getProduct() {
- return new FirstProduct();
- }
- }
- class FirstProduct implements Product {
- public function getName() {
- return 'The product from the first factory';
- }
- }
- class SecondFactory extends AbstractFactory {
- public function getProduct() {
- return new SecondProduct();
- }
- }
- class SecondProduct implements Product {
- public function getName() {
- return 'The product from second factory';
- }
- }
- $ firstProduct = AbstractFactory::getFactory()->getProduct();
- Config::$factory = 2;
- $secondProduct = AbstractFactory::getFactory()->getProduct();
-
- print_r($firstProduct-> getName());
- // The first product from the first factory
- print_r($secondProduct->getName());
- // 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:
- class Product {
- protected $id;
- public function __construct($id) {
- $this->id = $id;
- }
-
- public function getId() {
- return $this->id;
- }
- }
-
- class Factory {
-
- protected static $products = array();
-
- public static function pushProduct(Product $product) {
- self::$products[$product->getId()] = $product;
- }
-
- public static function getProduct($id) {
- return isset(self ::$products[$id]) ? self::$products[$id] : null;
- }
-
- public static function removeProduct($id) {
- if (array_key_exists($id, self::$products)) {
- unset(self::$products[$id]);
- }
- }
- }
-
-
- Factory::pushProduct(new Product('first'));
- Factory::pushProduct(new Product('second' ));
-
- print_r(Factory::getProduct('first')->getId());
- // first
- print_r(Factory::getProduct('second')->getId());
- / /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.
- interface Product {
- public function getName();
- }
- class Factory {
- protected $firstProduct;
- protected $secondProduct;
- public function getFirstProduct() {
- if ( !$this->firstProduct) {
- $this->firstProduct = new FirstProduct();
- }
- return $this->firstProduct;
- }
-
- public function getSecondProduct() {
- if (!$this- >secondProduct) {
- $this->secondProduct = new SecondProduct();
- }
- return $this->secondProduct;
- }
- }
-
- class FirstProduct implements Product {
- public function getName() {
- return ' The first product';
- }
- }
-
- class SecondProduct implements Product {
- public function getName() {
- return 'Second product';
- }
- }
-
-
- $factory = new Factory();
-
- print_r($ factory->getFirstProduct()->getName());
- // The first product
- print_r($factory->getSecondProduct()->getName());
- // Second product
- print_r($factory ->getFirstProduct()->getName());
- // 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.
- interface Product {
- }
- class Factory {
- private $product;
- public function __construct(Product $product) {
- $this->product = $product;
- }
-
- public function getProduct() {
- return clone $this->product;
- }
- }
-
- class SomeProduct implements Product {
- public $name;
- }
-
-
- $prototypeFactory = new Factory(new SomeProduct() );
-
- $firstProduct = $prototypeFactory->getProduct();
- $firstProduct->name = 'The first product';
-
- $secondProduct = $prototypeFactory->getProduct();
- $secondProduct-> name = 'Second product';
-
- print_r($firstProduct->name);
- // The first product
- print_r($secondProduct->name);
- // Second product
Copy code
Builder(构造者)
构造者模式主要在于创建一些复杂的对象:
- class Product {
- private $name;
- public function setName($name) {
- $this->name = $name;
- }
-
- public function getName() {
- return $this->name;
- }
- }
-
- abstract class Builder {
-
- protected $product;
-
- final public function getProduct() {
- return $this->product;
- }
-
- public function buildProduct() {
- $this->product = new Product();
- }
- }
-
- class FirstBuilder extends Builder {
-
- public function buildProduct() {
- parent::buildProduct();
- $this->product->setName('The product of the first builder');
- }
- }
-
- class SecondBuilder extends Builder {
-
- public function buildProduct() {
- parent::buildProduct();
- $this->product->setName('The product of second builder');
- }
- }
-
- class Factory {
-
- private $builder;
-
- public function __construct(Builder $builder) {
- $this->builder = $builder;
- $this->builder->buildProduct();
- }
-
- public function getProduct() {
- return $this->builder->getProduct();
- }
- }
-
- $firstDirector = new Factory(new FirstBuilder());
- $secondDirector = new Factory(new SecondBuilder());
-
- print_r($firstDirector->getProduct()->getName());
- // The product of the first builder
- print_r($secondDirector->getProduct()->getName());
- // The product of second builder
复制代码
Structural Patterns
Decorator(装饰器模式)
装饰器模式允许我们根据运行时不同的情景动态地为某个对象调用前后添加不同的行为动作。
- class HtmlTemplate {
- // any parent class methods
- }
-
- class Template1 extends HtmlTemplate {
- protected $_html;
-
- public function __construct() {
- $this->_html = "
__text__ ";
- }
-
- public function set($html) {
- $this->_html = $html;
- }
-
- public function render() {
- echo $this->_html;
- }
- }
-
- class Template2 extends HtmlTemplate {
- protected $_element;
-
- public function __construct($s) {
- $this->_element = $s;
- $this->set("
" . $this->_html . "");
- }
-
- public function __call($name, $args) {
- $this->_element->$name($args[0]);
- }
- }
-
- class Template3 extends HtmlTemplate {
- protected $_element;
-
- public function __construct($s) {
- $this->_element = $s;
- $this->set("" . $this->_html . "");
- }
-
- public function __call($name, $args) {
- $this->_element->$name($args[0]);
- }
- }
复制代码
Adapter(适配器模式)
这种模式允许使用不同的接口重构某个类,可以允许使用不同的调用方式进行调用:
- class SimpleBook {
- private $author;
- private $title;
- function __construct($author_in, $title_in) {
- $this->author = $author_in;
- $this->title = $title_in;
- }
-
- function getAuthor() {
- return $this->author;
- }
-
- function getTitle() {
- return $this->title;
- }
- }
-
- class BookAdapter {
-
- private $book;
-
- function __construct(SimpleBook $book_in) {
- $this->book = $book_in;
- }
- function getAuthorAndTitle() {
- return $this->book->getTitle().' by '.$this->book->getAuthor();
- }
- }
-
- // Usage
- $book = new SimpleBook("Gamma, Helm, Johnson, and Vlissides", "Design Patterns");
- $bookAdapter = new BookAdapter($book);
- echo 'Author and Title: '.$bookAdapter->getAuthorAndTitle();
-
- function echo $line_in) {
- echo $line_in."
";
- }
复制代码
Behavioral Patterns
Strategy(strategy mode)
The test mode is mainly to allow client classes to better use certain algorithms without knowing their specific implementation.
- interface OutputInterface {
- public function load();
- }
- class SerializedArrayOutput implements OutputInterface {
- public function load() {
- return serialize($arrayOfData);
- }
- }
-
- class JsonStringOutput implements OutputInterface {
- public function load() {
- return json_encode($arrayOfData);
- }
- }
- class ArrayOutput implements OutputInterface {
- public function load() {
- return $arrayOfData;
- }
- }
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. - interface Observer {
- function onChanged($sender, $args);
- }
- interface Observable {
- function addObserver($observer);
- }
- class CustomerList implements Observable {
- private $_observers = array();
- public function addCustomer($name) {
- foreach($this->_observers as $obs)
- $obs->onChanged($this, $name);
- }
-
- public function addObserver($observer) {
- $this->_observers []= $observer;
- }
- }
-
- class CustomerListLogger implements Observer {
- public function onChanged($sender, $args) {
- echo( "'$ args' Customer has been added to the list n" );
- }
- }
-
- $ul = new UserList();
- $ul->addObserver( new CustomerListLogger() );
- $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.
- interface Command {
- function onCommand($name, $args);
- }
- class CommandChain {
- private $_commands = array();
- public function addCommand($cmd) {
- $this->_commands[]= $cmd;
- }
-
- public function runCommand($name, $args) {
- foreach($this->_commands as $cmd) {
- if ($cmd-> ;onCommand($name, $args))
- return;
- }
- }
- }
-
- class CustCommand implements Command {
- public function onCommand($name, $args) {
- if ($name != 'addCustomer')
- return false;
- echo("This is CustomerCommand handling 'addCustomer'n");
- return true;
- }
- }
-
- class MailCommand implements Command {
- public function onCommand($name, $args) {
- if ($name != 'mail')
- return false;
- echo("This is MailCommand handling 'mail'n");
- return true;
- }
- }
-
- $cc = new CommandChain();
- $cc->addCommand ( new CustCommand());
- $cc->addCommand( new MailCommand());
- $cc->runCommand('addCustomer', null);
- $cc->runCommand('mail', null) ;
Copy code
|