Php Tutorial: php design patterns

Source: Internet
Author: User
Tags php oop
Abstract: When you constantly try to discover new features from your application, do you find that the solution you proposed and some things you have previously implemented are so... when you are constantly trying to discover new features from your application, do you find that the solution you proposed is so similar to something you have previously implemented? If you are a programmer (even if you start for a short time), you may answer "yes ". It seems that you have used some previous code to solve the newly discovered problems in the software development process. You may have realized that your solution is a basic principle and a method that is not only applicable to you but also widely used by all professional developers.

In fact, many program problems are constantly encountered, and many basic methods (or design patterns) used to solve these problems have emerged. The design pattern is a template that teaches you how to organize your code using authentic and reliable design.

Design Pattern History

The term "design patterns" was initially designed for the field of architecture. Christopher Alexander described some common architectural design problems in his 1977 book "A Pattern Language: Towns/Building/Construction" and explained how to use these existing, A collection of famous patterns to start a brand new effective design. Alexander's point of view is well transformed into software development, and long-term consensus is to use the original components to construct new solutions.

All design patterns have some common features: a name, a problem statement, and a solution ).

The identifier of a design pattern is important, because it allows other programmers to understand the purpose of your code immediately without having to study it too deeply (at least the programmer will be familiar with this pattern through this identification ).

The problem description is used to describe the application fields of this model .?

The solution describes the execution of this model. The discussion of a good design model should cover the advantages and disadvantages of using this model.

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

For example, the color, style, and size of a shirt you buy from a store is determined by the designer and manufacturer, but it meets your needs.

However, if there are no clothes in the store that suit you, you can create your own shirt (design its shape, select the fabric, and then make a tailor together ). But if you are not a tailor, you may find it easy to find a proper pattern and then design your shirt according to the pattern. With a model, you can get a well-designed shirt in less time.

Back to the discussion Software, a data extraction layer or a CMS (content management system) is a library-it was previously designed and encoded, if it meets your needs accurately, it is a good choice. But if you are reading this book, you may find that the inventory (original) solution is not always effective for you. So far you know what you want, and you can implement it, you only need a model to guide you.

Last thought: like a tailor model, a design itself is useless. After all, you cannot wear a clothing model-it is simply pieced together by thin paper. Similarly, a software design model is just a guide. It must be specifically designed based on the programming language and the characteristics and requirements of your application.

Objectives of this book

The purpose of this book is not to comprehensively introduce various types of software design patterns, nor to develop a new design patterns or terminology, but to highlight some existing well-known design patterns. This book introduces some design patterns that I think are helpful for developing dynamic WEB applications, and shows how to implement these design patterns in PHP.

Object-oriented programming (OOP)

One advantage of this book is that all ideas are based on the natural design model of OOP and implemented using OOP.

If you are not familiar with OOP, there are many related resources (books, websites, magazines, classes, etc.) to help you better understand it. Most OOP materials praise its benefits-code reuse, robust code, code encapsulation, polymorphism, and scalability. of course, all these are also very important and useful. However, I think the main advantage of OOP is how it inspires you to break down the problem into easy-to-handle modules. Clear design and implementation into small modules, so that your code can be thoroughly tested and easier to understand and maintain.

Reader skill requirements

This book assumes that you can use PHP smoothly. In particular, this book assumes that you have learned how to operate PHP and PHP syntax and how to execute PHP code with OOP. This book is not an introduction to PHP programming, nor is it intended to introduce php oop programming.

Since not all OOP developers use the same term, I will define it in the text or toolbar when new terms are introduced.

PHP4 and PHP5

When I wrote this book, PHP5 had been released for some time, but it was not widely used by public groups. In my own work, I have started to migrate the new application development work to the PHP5.0.3 environment, so far, I am very happy to find that PHP5 has good backward compatibility with the code of PHP4, and it faces the object model as one of the most meaningful new features of PHP5.

There are a lot of good articles and guides to handle the nuances between object models in different PHP versions. But in simple terms, PHP5 provides:

Object handle (which will be explained below. For more details, see Chapter 2: Value of object model )?

Better constructor (uniform name, cannot be changed )?


Visibility (public exposure of methods and properties, protected by protected, private )?

Exception handling (you can select the new syntax try {} catch {} to trigger the error )?

Static class?

Image (dynamic check class, method, attribute )?

Type hiding?

PHP5 also provides some more fuzzy features:

New magic methods?

_ Get () and _ set () allow you to control variable access

_ Call () allows you to dynamically intercept all the properties of the called object.

_ Sleep () and _ wakeup () allow you to reload serialization methods.

_ ToString () allows you to control how to use a string to describe the object itself.

Automatically load Autoloading (when the class is objectized for the first time, the user is allowed to automatically load the class )?

Final (this method or a class cannot be overloaded by its subclass )?

Object handle

The best feature of PHP5 is to use a handle to define a class, similar to a file or database handle. Using an object in a PHP function does not implicitly copy this object, but provides an operation handle.

To better understand the differences, we consider the following two examples:

// PHP4 class
Class ExampleP1 {
Var $ foo;
Function setFoo ($ foo ){
$ This-> foo = $ foo ';
Function getFoo (){
Return $ this-> foo;
Function changeExample ($ param ){
$ Param-> setFoo ('blah ');
Return $ param-> getFoo ();
$ Obj = new ExampleP1;
$ Obj-> setFoo ('bar ');
Echo $ obj-> getFoo (); // bar
Echo ChangeExample ($ obj); // blah
Echo $ obj-> getFoo (); // bar

In PHP4, the variable $ param in changeExample () is a copy of $ obj. Therefore, this function does not change the value of $ foo in the original object, in this way, $ obj-> getFoo () outputs 'bar '.

In PHP5, because $ obj is only an object operation handle in the function, the same changeExample () function actually affects the original object. In other words, you no longer need to copy the image with the handle, and $ param is the $ obj instance.

// PHP5 class
Class ExampleP2 {
Protected $ foo;
Function setFoo ($ foo ){
$ This-> foo = $ foo;
Function getFoo (){
Return $ this-> foo;
$ Obj = new ExampleP2;
$ Obj-> setFoo ('bar ');
Echo $ obj-> getFoo (); // bar
Echo ChangeExample ($ obj); // blah
Echo $ obj-> getFoo (); // IMPORTANT, produces blah

When you use the $ this variable in other objects or the built-in construct of this object (_ construct), this problem becomes more complex.

The result is in PHP4, which is almost always required:

Create a reference object like this $ obj =? & New class;

Call a reference object in a function, such as function func (? & $ Obj_param ){}

Capture objects by referencing functions, such as functions? & Some_func () {}$ return_obj = & some_funct ()

In fact, in some cases, you also need to copy the original object. In my PHP4 code, I always make it clear to copy comments for any non-referenced object task as an obvious object. For a long time, such a short comment can greatly reduce the headache of any person who maintains your code (note: This code is highly maintainability ). Reference and pass-through values. the knowledge about object handles and object replication will be explained in detail in Chapter 2 "value of object mode.

Although I personally prefer to use PHP5 for development, I feel that PHP4 will continue to be used for a long period of time, and the existing public release projects will continue to support PHP4. Therefore, this book provides the same support for the two versions of PHP. Try to provide two versions of instance code: PHP4 and PHP5. In each chapter, each code block (changed in different PHP versions) provides corresponding annotations to imply changes, such as // php4 and // php5.

Bibliography and other resources

There are many reference books to help you better learn design patterns. The "bible" of the design model (translated by translator: the best book) is Erich Gamma, Richard Helm, ralph Johnson and John Vlissides (his pioneering work is often referred to as "Gang of Four" abbreviated as "GOF", which represents the Four of them) write the design model: reusable Object-Oriented Software development principles.

The next most useful book on the design Patterns of php web applications is Patterns of Enterprise Application Architecture published by Martin Fowler: enterprise Application Architecture Model ). Compared to the GOF book containing all general design patterns, Fowler's book details many design patterns specifically used to develop web applications.

In addition, many websites also provide a wealth of resources for design patterns, a particularly typical site is the Portland model Library ( ).

Another site for PHP design patterns is phpPatterns, and the online address is


I am very grateful to my boss for allowing me to spend part of my time in this field of interest, I would also like to thank him for providing me with knowledge and experience so that I can write this book with confidence.

Another source of my inspiration, thoughts, and experience is the SitePoint forum for this site ( It is particularly worth mentioning that the contributors who often post "Advanced PHP Forum" (translated by translator: PHP Advanced Forum) have a wealth of knowledge and experience, they are the most generous group I found on the Internet that shares my thoughts. I 've also logged on to SimpleTest (, WACT (http: //, and many other PHP engineering projects that I think are priceless through these resources. In the following years, I hope that SitePoint will continue to become a rich resource point for PHP developers.

Without the contributions and important efforts of the PHP development team, this book is obviously impossible. It is precisely because they developed a language that is so easy to use, easy to learn, universal, and very suitable for developing WEB applications.

Finally, I would like to thank all the members of Marco Tabini and php | effecect. This magazine (Translator's note: php | effecect) has become a source of many different PHP topics, and these topics are published by professional developers. Meetings sponsored by Macro and the company are also quite good.

The above is the php Tutorial: Preface to the php design model. For more information, see PHP Chinese website ( )!

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: 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.