PHP design Pattern Notes--summary

Source: Internet
Author: User
Tags zend framework

First, the introduction

General definition of design patterns no longer say, just about the design patterns I understand, the main purpose of my understanding of design patterns is to make the code more extensible , easy to reuse , and easy to maintain , using object-oriented (classes, interfaces, etc.) features. These three features also require that we do not accumulate too many functions into one class, but rather assign them to more classes. Therefore, 20 or more design patterns are mainly designed around the above four purposes.

PHP design mode This book is about 19 design patterns, but in fact, most of the design patterns of thought or design is the same thinking and form, I will be categorized and summarized below, so as to facilitate a better understanding of the book, but it is best to look at this book, the use of the example is relatively simple, Remember this book to read in order to simplify the code, some should be implemented through the interface to more standardized places without interface.

  (Note: Since this article is a summary of the PHP design model, so the example of the time reason book I have mentioned but not written in this article, you can view the ebook, I will also introduce the various models of the article or the article to supplement the example)

Second, the model to be considered when creating the class

The final concept of object-oriented is class, which is an important step from process-oriented transformation to object. So creating a class, how dependencies between classes are implemented, is a very important issue, and the following are some of the patterns that address this problem.

1. Builder mode

We should try to minimize the appearance of new in our code, which is an important way to create a class, but we should let him appear in the builder or factory as much as possible, rather than in a method of a class. Cause one, perhaps the initialization of this class is troublesome, not only need new, but also to its new constructor inside the parameter, then we must first establish those parameters, and those parameters may have objects need new, this initialization operation is particularly long, cause two, it is possible that the class later needs may change, Then the initialization operation we need to change, the operation of the change is also carried out in other classes, which does not conform to the principle of independence between the various classes.

2, Factory mode-extension of the builder model

When a lot of code and frameworks say Factory mode, what it does is builder mode, and I think the meaning of the factory model is more of an abstract factory that makes the builders ' patterns more resilient. Then the concept of builder mode, if some classes have a set of standard to create process, then we can build an abstract project, and then each concrete class inherit this class, Pizza Factory is a good example.

3, Supplement: The concept of service-the core of many PHP frameworks, the implementation of dependency injection. Dependency injection is important, and I'll explain it in other articles.

If we look at the two main frameworks of Php Symfony and the Zend Framework we will find that there is a very important concept called Dependency Injection (Dependency injection), that is, if the problem of dependency between classes is resolved, there is an important concept in the way of implementation called Service, or service container. In my understanding this is similar to the factory model, ZF can also point a service to a specific factory, and in the factory class we can also implement the abstract factory, so that the two are conceptually similar, but do not conflict in the way. will be introduced separately later.

Third, when the need to change or increase the function

The following patterns allow us to reuse code

1. Adapter mode

We say that when a function changes, we should ensure that the interface of the class does not change, so that when a class changes, it does not need to change the code of the class that uses or uses it. However, after all, there will be code and classes that violate this principle, such as the example in the book, the function of decomposing errorobject should be implemented by the class logtocsvadapter that the demand changes, but it may be for many reasons (such as the code is immutable, not open source), did not do so. The adapter mode is used to deal with this situation, he can be through extend (such as the use of the book), you can also use it as a member variable to re-implement an interface that meets the requirements.

2. Adorner mode

Form: The decorated class is used as its member, and the method is called through the member.

You can use this mode when you want to add functionality to a class but are afraid to break a class, but this idea will not solve the problem fundamentally.

Another common scenario is if you only want to show some functionality to someone else in this class, not all of them.

3. Broker mode (similar to event mode)

Form: Multiple connected classes use the Mediator class as their member, and calling a method will change the state of all classes registered in the mediator by the mediator, so the registered class needs to implement an interface for the mediator to invoke.

Similar to those of observers.

Structurally similar to the event pattern, except that registration is written dead (hardcode) in the intermediary (corresponding to the register machine in the event), but its problem-solving approach is a special case of the event, so called the mediator mode.

Suppose there is a class, and another class is parallel in the concept and the first class (perhaps a class from the beginning, or a class that arises with the change in demand), the two classes have a connection, and one class change needs to change the state of the other class, which requires intermediaries. Specific examples are described in the event pattern.

Iv. dispersing functionality into more classes

The actual project, maintaining a lot of functions of the "big" class is very troublesome, this does not conform to the principle of cohesion poly-low coupling, a class if the more features, then the more process-oriented, the relationship between the more closely, in fact, object-oriented to solve the main problem is how to use more manageable ways to distribute the functionality into more classes Sounds simple, in fact, if the use of a bad way to split the class will be more chaotic, in a sense this is the design pattern appears. And for example, a person is responsible for maintaining a class that is responsible for this class of tests, and if the results change every time a function changes the test code of this class, if we distribute the functionality to more classes, we can guarantee that the test code of the class will not change.

1, the event mode ( will write a separate article detailed introduction, here Introduction )

A lot of people, including my impression of the event. In the window process, we click the mouse or button will have an event, it will change all registered the object of the event, it may be the view changes, it may be our own definition of a function, the mediator pattern is similar to the event pattern, It's just that all registrations in intermediaries are equal, such as a table and a histogram, and we change the contents of the table to cause the histogram to change, and shortening the length of the histogram will change the contents of the table. But what is the use of event patterns and mediator patterns in general application logic?

We want to put aside the meaning of the event mentioned above, which is just a special case of the event, which illustrates the more general use of the event. In fact, the event is essentially a mediator pattern, where the intermediary is placing the registered container in the class that needs to be changed, equivalent to the object in the event, but some classes are not designed to be a mediator in the first place, that is, the class does not have a member of a mediator, possibly because the need is not expected, It may also be that it is troublesome to add this mechanism to the class, but instead chooses an event pattern that can implement the same functionality outside the class. (So the mediator mode can be converted into event mode, although the event pattern eliminates the trouble in the class, but it needs to provide a set of event mechanism, relative to the intermediary in the outside of the class more troublesome, but because of the separation into the class, so there are a lot of ready-made intermediary implementations, such as the framework of the basic implementation of this mechanism , Symfony is able to use this component in a framework that is not symfony.

In addition to the above view interface, other examples may not be so intuitive, not so consistent with the name of the event, its main role as written in the headline, it is the code structure of the event pattern to better partition the code of the function to make it easier to manage. So to understand, we should forget the general meaning of events. Think of a more complex logic example, a telephone company will calculate the cost of the user's call record, it is well known that this is a very complex logic, according to the user's different packages and the use of the region will have a difference, then a long series of logic judgment code we have to write in a class? Certainly does not conform to our principles, then we use the form of the event pattern (repeated emphasis only on form) to implement the logic into different classes. We have all the telephone services as listener, register, each call log as subscriber, through the IF statement to determine which business belongs to, and then to those business Dispatch,listener to get the Bill object, to change it, The final billing object is the final billing information. Through the event model, we divide the different processing logic into listener objects, which is more convenient for later extension.

The above example is to modify the object through the listener, or can only be used to obtain object information for related operations, such as blog Park to publish a post will have a lot of operations, such as the need to save the database, need to do the inverted operation, need to do the label operation, if you want to publish to the first page also need a series of operations, Some listener can be used to listen to the release of the blog post this operation, itself does not modify the post of the object, but the use of post object information to operate.

Back to more general parlance, the event pattern is mainly applied in plugins (plugin), which are of course more generalized plugins. This is Symfony's introduction consider the Real-world example where you want to provide a plugin system for your project. A plugin should be able to add methods, or does something before or after a method was executed, without interfering with oth ER plugins. This isn't an easy problem to solve with single and multiple inheritance (were it possible with PHP) have its own drawback S.

In the sense above, events are a mechanism for processing and processing objects in a more extensible way, and you can use events when you want to use this mechanism, and with the event components in an existing framework, you can convert both the observer and the mediator into an event pattern, so events are often used in C # Can be reflected in the importance of the event.

You can also take a look at the Symfony event documentation to learn about the use of events.

2. Observer mode

Form: $this->obserber->update ($this), while the mediator is in the form of $this->mediator->chage ($this, Array (' band ' = $newname)). You can see that it's just to accomplish two different functional requirements. Both can be replaced by an event that sends an update event, which sends a Changebandname event, and then realizes the change by looking at the name of the incoming object.

3. Entrustment mode

By assigning or delegating to other objects, the delegate design pattern can remove the judgments (if statements) and complex functionality in the core object. Similar to the concept of delegation in C #, C # is a function that passes a delegate as a parameter to another function to divide functionality into other equations. An object-oriented delegate is a function that is divided into a delegate class.

Form: The delegate class has a member variable of a delegate class.

4. Strategy mode

When you can create interchangeable objects that are applied to object-based, self-contained algorithms, the best practice is to use the policy model.

And the Commission model is basically consistent, both in form and in meaning, but the example of the book model is to transfer the $this->playlist to the delegate mode, but the strategy mode has passed the whole $this to the policy mode.

The strategy model also has an important meaning, if a method of a class is not used frequently, can be converted into a policy mode, so that it does not have to test the class every time.

5. Agent Mode

The proxy pattern can have different forms, as long as it is given the meaning of "agent". The book implements the proxy through the inheritance form of the decorator.

V. Other

The following are very common patterns

1. Object-oriented pattern--template mode

It is not described in detail, and abstract classes and interfaces are an idea.

2. Appearance mode (facade)

Facade this word is common in the naming of classes in some frameworks, similar to the role of process-oriented functions, encapsulating a series of code for a particular function into a static method in a class, which is usually the only method of this class.

3, public methods abstract into class--data Access object schema

The public method abstract class is an object-oriented basic principle, not only an entity, if it is a function can be used by more than one entity or function, then we should be a separate class for him, other classes if you use it that is referred to as the dependency injection (dependency injection).

The data Access object pattern is also a basic practice of this pattern. Can be combined with Zend Famework's Guide http://framework.zend.com/manual/current/en/in-depth-guide/preparing-db-backend.html to understand. Basically in order to encapsulate the operation of the data, Tablegateway is also a mature pattern in this area, basically a table a class, but this also restricts the database itself connection operation, we can only through the operation between classes to achieve the connection, I will write in other articles.

4, the system only need a single-element mode

This pattern is also very common

Six, the key sentence notes in the book

1, the connection of different objects is the goal of simplification

PHP design Pattern Notes--summary

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.