Introduction to PHP design patterns [concept, classification, principles, etc.]


This article describes the PHP design pattern. For your reference, the details are as follows:

1. Design pattern

Design pattern is a set of repeated use, most people know, after classification cataloging, code design experience summary. Design patterns are used to reuse code, make it easier for others to understand, and ensure code reliability. No doubt, the mode of software design is more than that of others.
The classic definition of patterns: each pattern describes a problem that is constantly emerging in our environment, and then describes the core of the solution to the problem. In this way, we can reuse the existing solutions countless times without repeating the same work. Pattern is a solution to a problem in a specific environment

2. Purpose of design pattern

The goal is to teach you how to use authentic and reliable design to organize code templates. In short, it is the general excellent experience summarized and abstracted by predecessors in the process of programming. The main purpose is to increase the flexibility and reusability of the program. On the other hand, it also helps to standardize the program design and improve the system development progress.

Some people also advise: don’t pay too much attention to the “design pattern” of the program. Sometimes it’s easier to write a simple algorithm than to introduce a pattern. In most cases, the program code should be easy to understand, even the cleaners can understand. However, in large projects or frameworks, there is no design pattern to organize code, which is difficult for others to understand.

A software design model is just a guide. It must be specially designed according to the characteristics and requirements of the programming language and your application.

3. Design pattern history

The term “design pattern” was originally designed for use in the field of architecture. In his 1977 book “a pattern language: towns / building / construction”, Christopher Alexander describes some common architectural design problems and explains how to use these existing, famous pattern sets to start a new and effective design. Alexander’s point of view has been well translated into software development, and has long been willing to use the original components to construct new solutions.

4. Four basic elements of design pattern

Design patterns make it easier for people to reuse successful designs and architectures. Expressing proven technologies as design patterns will also make it easier for new system developers to understand their design ideas.

All design patterns have some common features: aidentification(a pattern name), aProblem statement(a problem statement) and aSolution(a solution),effect(consequences)

Pattern name: describes the problem, solution and effect of the pattern

A design pattern identifier (pattern name) is important because it allows other programmers to immediately understand the purpose of your code without having to learn too much (at least through this logo, programmers will be familiar with the pattern). Without this model name, we can not communicate design ideas and design results with others.

ProblemDescription is used to illustrate the domain of application of this pattern.

Describes when patterns should be used. It explains the design problems and the causes and consequences of the problems. It may describe the specific design problems, such as how to express algorithms with objects. It may also describe the class or object structure that leads to inflexible design. Sometimes, the problem section includes a set of prerequisites that a usage pattern must satisfy.

SolutionDescribes the implementation of this model.
This paper describes the components of the design, the relationship between them, their respective responsibilities and cooperation methods. Because a pattern is like a template, which can be applied in many different situations, the solution does not describe a specific and specific design or implementation, but provides an abstract description of the design problem and how to solve the problem with a general combination of elements (class or object combination).

Effects (sequences)

This paper describes the effect of pattern application and the problems that should be weighed when using pattern. Although we do not always mention the effects of patterns when describing design decisions, they are important for evaluating design choices and understanding the costs and benefits of using patterns. Software effects mostly focus on the measurement of time and space, and they also express language and implementation issues. Because reuse is one of the elements of object-oriented design, pattern effects include its impact on the flexibility, extensibility or portability of the system. It is helpful to understand and evaluate these patterns to list these effects explicitly.A good design pattern discussion should cover the advantages and disadvantages of using this model.

A pattern is an effective way to solve specific problems. A design pattern is not a library (a code base that can be directly included and used in your project) but a template (java bean) used to organize your code. In fact, there are many differences between a code base and a design pattern in application.

For example, a shirt you buy from a store is a code base. Its color, style and size are determined by the designer and manufacturer, but it meets your needs. However, if there is nothing in the store that suits you, you can create your own shirt (design its shape, choose the fabric, and then tailor it together). But if you’re not a tailor, you may find it easy to find the right pattern and design your own shirt according to this pattern. With a model, you can get a skillfully designed shirt in less time.

Back to the discussion software, a data extraction layer or a CMS (content management system) is a library – it has been designed and coded before. If it can accurately meet your needs, it is a good choice. But if you’re reading design patterns, you may find that inventory solutions don’t always work for you. So far you know what you want, and you can implement it, you just need a model to guide you.

One last thought: like a tailor model, a design is useless in itself. After all, you can’t wear a dress model – it’s just made of very thin paper. Similarly, a software design model is just a guide. It must be specially designed according to the characteristics and requirements of the programming language and your application.

3. Design pattern classification

1) According to the purpose (what the pattern is used for), it can be divided into three types: creative, structural and behavioral
Create patternIt is mainly used to create objects.
Structural modelIt is mainly used to handle the combination of classes or objects.
Behavioral modelIt is mainly used to describe how to interact with classes or objects and how to assign responsibilities.

2) According to the scope, i.e. whether the schema is mainly used to handle the relationship between classes or objects, it can be divided into class pattern and object pattern

Class pattern: deals with the relationships between classes and subclasses. These relationships are established by inheritance and are determined at compile time. They are static.
Object pattern: deals with the relationships between objects, which change at runtime and are more dynamic.

4. Some basic design patterns (Baidu Encyclopedia)

Abstract factory: provides an interface to create a series of related or interdependent objects without specifying their concrete classes.

Adapter: converts the interface of one class to another that the customer wants. The a d a p t e r pattern enables classes that would otherwise not work together due to interface incompatibility to work together.

Bridge: separates the abstract part from its implementation part so that they can be changed independently.

Builder (builder pattern): separate the construction of a complex object from its representation, so that different representations can be created in the same construction process.

Chain of responsibility: in order to decouple the sender and receiver of a request, multiple objects have the opportunity to process the request. Connect these objects into a chain and pass the request along the chain until an object processes it.

Command (command mode): encapsulates a request into an object so that you can parameterize customers with different requests, queue or log requests, and support cancelable operations.

Composite composition pattern: objects are combined into a tree structure to represent a “part whole” hierarchy. It makes the use of single object and composite object consistent.

Decorator decorator: dynamically add additional responsibilities to an object. In terms of extension function, it is more flexible than subclass generation.

Facade (facade pattern): provides a consistent interface for a set of interfaces in a subsystem. The f a C a d e pattern defines a high-level interface, which makes the subsystem easier to use.

Factory method factory method: define an interface for creating objects and let subclasses decide which class to instantiate. Factory method delays the instantiation of a class to its subclasses.

Flyweight: using sharing technology to support a large number of fine-grained objects.

Interpreter: given a language, define a representation of its grammar and define an interpreter that uses that representation to interpret sentences in the language.

Iterator iterator: provides a way to access elements in an aggregate object sequentially without exposing the internal representation of the object.

Mediator: a mediation object is used to encapsulate a series of object interactions. Mediators make objects not need to refer to each other explicitly, so that they are loosely coupled and can change their interactions independently.

Memento (memo mode): capture the internal state of an object and save the state outside the object without breaking encapsulation. This will restore the object to its saved state later.

Observer mode: defines a one to many dependency relationship between objects so that when an object’s state changes, all objects that depend on it are notified and automatically refreshed.

Prototype: use the prototype instance to specify the kind of object to be created, and create a new object by copying the prototype.

Proxy: provides a proxy for other objects to control access to this object.

Singleton: ensures that a class has only one instance and provides a global access point to access it.

State: allows an object to change its behavior when its internal state changes. Object appears to have modified the class it belongs to.

Strategy: define a series of algorithms, encapsulate them one by one, and make them replaceable. This pattern makes the change of algorithm independent of the customers who use it.

Template method: defines the skeleton of the algorithm in an operation and delays some steps to subclasses. Template method enables subclasses to redefine some specific steps of an algorithm without changing its structure.

Visitor pattern: represents an operation that acts on elements in an object structure. It allows you to define new operations on elements without changing their classes.

5. Six principles of design mode

1) The core principle of design pattern is: Open – Closed Principle (OCP): open to extension and close to modification

It means that in a system, the extension is open and the modification is closed. A good system can extend your functions without modifying the source code. The key to realize the open and close principle is abstraction

By extending the existing software system, new behavior can be provided to meet the new requirements of software, and the changing software has certain adaptability and flexibility. The existing software module, especially the most important abstract layer module, can not be modified, which makes the changing software system have a certain stability and continuity.
In the “open close” principle, the abstract class or interface is not allowed to be modified, while the concrete implementation class is allowed to be extended. Abstract classes and interfaces play an extremely important role in the “open close” principle.. that is, to predict the possible changing requirements and to foresee all possible known extensions.. so “abstraction” is the key here!!!

The closed principle of variability: find out the variables of the system and encapsulate them. This is the best implementation of the “open close” principle. Don’t put your variables in multiple classes or scattered in every corner of the program. You should envelope the variable factors. And do not wrap the variables used together. The best solution is to, Block envelope, your variable factors! Avoid the appearance of super class, super long class and super long method! Add artistic flavor to your program, and make the program artistic is our goal!!

2) Richter’s substitution principle: any base class can appear, subclass can also appear

Liskov Substitution Principle: the subclass must be able to replace the base class from where it appears. Subclasses can also add behavior to the base class. This Yi refers to the relationship between the base class and the subclass. Only when this relationship exists, can the principle of Richter’s substitution exist. A square is a rectangle, which is a classic example of understanding the principle of Riemannian substitution.

3) Dependency Inversion Principle: rely on abstraction, not on concrete implementation

The principle of dependency inversion principle is to rely on abstraction, not on concrete. In short, the dependency inversion principle requires the client to rely on abstract coupling. Statement of principle:

(1) Abstract should not depend on details; details should depend on abstraction;
(2) Program for the interface, not for the implementation.

If the principle of opening and closing is the goal, the principle of relying on inversion is the means to reach the principle of opening and closing.. if you want to achieve the best “opening and closing” principle, you should abide by the principle of dependence reversal as far as possible.. it can be said that the principle of dependence reversal is the best criterion for “abstraction”! I feel that the principle of reliance reversal is also a supplement to Richter’s principle of substitution, It should be easy to understand the principle of dependency reversal

4) Composition / aggregation Reuse Principle (carp): try to use composition / aggregation principle instead of inheritance relationship to achieve the purpose of software reuse

Composite / Aggregate Reuse Principle (carp) is often called composite Reuse Principle (CRP). It is to use some existing objects in a new object to make it a part of the new object. New objects reuse existing functions through delegation to these objects. In short, use composition / aggregation as much as possible and avoid inheritance as much as possible.

We should try to use composition / aggregation principle instead of inheritance relationship to achieve the purpose of software reuse. This principle and Richter’s substitution principle complement each other. Both of them are the norms to realize the “open close” principle. If we violate this principle, we can’t realize the “open close” principle. Let’s first see what is synthesis and what is polymerization

What is synthesis?
For example, his furniture has nothing to do with his own house, It is the same as black chicken and top-grade medicinal materials. For example, weapons and equipment in online games are synthesized, and many things are combined into a super strong thing

What is aggregation?
Aggregation: aggregation is a stronger dependence than synthetic relationship. Aggregation is a part of a whole to an individual, for example, the relationship between a Mercedes Benz S360 car, a Mercedes Benz S360 engine, and a Mercedes Benz S360 tire. These relationships have the nature of aggregation. Because Mercedes Benz S360 engine and Mercedes Benz S360 tire can only be used by Mercedes Benz S360, leaving Mercedes Benz S360, In our design, such relationship should not appear frequently. This will increase the coupling degree of design
Understand the relationship between composition and aggregation, and then understand the principle of composition / aggregation. To avoid appearing in system design, the inheritance level of a class is more than three times. If so, you can consider refactoring your code or redesigning the structure. Of course, the best way to do this is to consider using the composition / aggregation principle

5) Dimitar’s Law: classes in the system should not interact with other classes as far as possible to reduce the coupling between classes

Law of Demeter (LOD) is also called the least knowledge principle (LKP), that is, an object should know as little as possible about other objects.

Other expressions: only communicate with your direct friends, don’t talk to “strangers.”. A class should know the least about the classes it needs to couple or call. It’s none of my business to know how complicated the internal structure of you (the coupled or called class) is. It’s your business. I know that you provide public methods. I call so many, and I don’t care about anything else.

Dimitar’s law and design pattern facade and mediator make people ignorant

Classes in the system should not interact with other classes as far as possible, so as to reduce the coupling between classes. In your system, when expanding, you may need to modify these classes. The relationship between classes determines the complexity of modification. The more interactions, the more difficult it is to modify. On the contrary, if the interaction is smaller, the difficulty of modification will be less. For example, class a depends on class B, Then class B depends on class C. when you modify class A, you should consider whether class B will be affected, and whether the impact of class B will affect class c.. If class C depends on class D again at this time, ha ha, I think some of such modifications are affected

6) Interface isolation Law: This Law is similar to Dimitar’s law

The principle of interface segregation is that it is better to use multiple specialized interfaces than to use a single total interface. In other words, from the perspective of a customer class, the dependency of one class on another should be based on the minimum interface.

An interface that is too bloated is a pollution to the interface. Customers should not be forced to rely on methods they do not use.

In order to achieve as little coupling as possible, we need to use the interface to standardize the class, and use the interface to constrain the class. To achieve the requirements of the dimit rule, it is best to implement the interface isolation law, and implement the interface isolation law, and you will meet the Dimitar law

6. Summary

Design pattern is a successful design scheme which can realize maintainability reuse from many excellent software systems. Using these schemes will avoid us to do some repetitive work, and can design high-quality software system.

The main advantages of the design pattern are as follows:

1) Design pattern integrates the experience of many experts and is used by developers in a standard form. It provides a set of common design vocabulary and a common language to facilitate communication and communication between developers, making the design scheme more understandable. For developers and designers who use different programming languages, design patterns can communicate system design schemes. Each pattern corresponds to a standard solution. Design patterns can reduce the complexity of developers’ understanding of the system.

2) Design patterns make it easier for people to reuse successful designs and architectures. Expressing proven technologies as design patterns will also make it easier for new system developers to understand their design ideas. Design patterns make it easier to reuse successful designs and avoid those that lead to non reusable designs.

3) Design patterns make the design more flexible and easy to modify.

4) The use of design patterns will improve the development efficiency and quality of software system, and save the design cost to a certain extent.

5) Design patterns can help beginners understand the object-oriented idea more deeply. On the one hand, it can help beginners to read and learn the source code of existing class libraries and other systems more easily, on the other hand, it can also improve the design level and code quality of software.

Design patterns are not learned, they are used. Learning in order to learn design patterns may not work well. General frameworks use design patterns. For example, the ZF of PHP is used for many design patterns. The class name or directory name in the framework is named after a certain design pattern. As soon as you see the class name or file name, you will know its code organization structure. If you are proficient in language, the rest of the coding is naturally very simple. With the accumulation of coding experience, the understanding of design patterns and principles will become more thorough. The process is that there is no way to doubt and the result is a village full of hidden flowers.

In addition, it should be noted that after proficient in the mode, do not go to the mode due to mode 2. If it looks likeHua Luogeng, a famous mathematician, said that “reading is a process from thin to thick, and then from thick to thin”. That means you’ve got it.

18 principles of excellent programming

Good programming principles are closely related to good design engineering principles. This article summarizes these design principles to help developers write code more efficiently and help them become good programmers. Diggins is a Canadian senior technician with 25 years of programming experience. He has worked for Microsoft and Autodesk, and founded two profitable Internet companies.

1. Dry – don’t repeat yourself

The basic principle of programming is to avoid repetition. There are always many structures in program code, such as loops, functions, classes, and so on. Once you repeat a statement or concept, it’s easy to form an abstraction.

2. Abstract principle

Related to dry principle. Remember that every important function in the program code can only appear in one place in the source code.

3. Keep it simple and stumped

Simplicity is the goal of software design. Simple code takes less time, has fewer vulnerabilities and is easy to modify.

Avoid creating a YAGNI (you are’t going to need it)

Don’t create new features unless you need it.

5. Do the simplest thing that could possibly work

Do the simplest thing that works. In programming, be sure to keep the principle of simplicity. As a programmer, constant reflection on “how to simplify at work?” will help keep the simple path in design.

Don’t make me think

This is the title of a book by Steve Krug, and it’s also about programming. The code must be easy to read and understand, so that others will appreciate it and give you reasonable suggestions. On the contrary, if it is complicated and difficult to understand the program, others will always avoid it.

7. Open / closed principle

The software entities you write (classes, modules, functions, etc.) should be open source, so that others can develop. However, for your code, you have to limit others not to modify. In other words, other people can write based on your code, but they can’t modify your code.

8. Write code for the maintainer

A good code should enable me or others to continue to write or maintain it in the future. Code maintenance, perhaps I will be easier, but it is more troublesome for others. So make sure that your code is as easy to maintain as possible. “If a maintainer doesn’t continue to maintain your code, it’s likely that he will have the urge to kill you.”

9. Principle of Least Surprise

The principle of least surprise is usually referred to in the user interface, but it also applies to code written. Code should be as small as possible to surprise readers. In other words, the code you write only needs to be written according to the requirements of the project. Other gorgeous functions are not necessary, so as not to be self defeating.

10. Single responsibility principle

The function of a code should ensure that there is only a single and definite execution task.

11. Minimize coupling

Any part of the code should be less dependent on other region code. Try not to use shared parameters. Low coupling is often the symbol of perfect structural system and excellent design.

Maximum cohesion principle

Similar function code should be placed in one part as far as possible.

13. Hide implementation details

The principle of hiding implementation details can minimize the impact on other components when other functional parts change.

14. Dimitri’s law is also called the law of Demeter

The code is only connected to parts that are directly related to it. (for example: the class inherited from this part, the object contained, the object passed by the parameter, etc.).

15. Avoid premature optimization

Don’t optimize unless your code runs slower than you think. If you really want to optimize, you have to figure out how to use data to prove that it’s faster.

“Premature optimization is the root of all evils” — Donald Knuth

16. Code reuse is good

Reusing code can improve the readability of code and shorten the development time.

17. Separation of concerns

Functions in different fields should be composed of different codes and modules with minimum overlap.

18. Embrace change

This is the title of a book by Kent beck and is also considered the tenet of extreme programming and agile methods.

Many other principles are based on the concept that you should be positive about change. In fact, some older programming principles, such as the minimum coupling principle, are designed to make code easy to change. Whether you’re an extreme programmer or not, writing code based on this principle will make your work more meaningful.


I hope this article will help you with PHP programming.