PHP Tutorial: The preface to PHP design patterns

Source: Internet
Author: User
Tags php programming
When you're constantly trying to discover new features from your application, do you find that the solution you're proposing is similar to something you've already implemented in the past? If you are a programmer (even if you start a short time), you may be able to answer "yes". It seems that you have used some of the previous code to solve the new problems that are discovered in the software development process. You may have realized that your solution is the basic principle, a method that is more than just you and is a widely repeated application for all professional developers.

In fact, many of the procedural problems are constantly recurring, and many of the basic methods used to solve these problems (or design patterns) have surfaced. Design patterns are a template that teaches you how to organize your code with real and reliable design.

Design Pattern History

The term "design pattern" was originally designed for the field of architecture. Christopher Alexander in his 1977 book, "A Pattern language:towns/building/construction", which describes some common architectural design problems and explains how to use them, A well-known collection of patterns to start a new and effective design. Alexander's view is well translated into software development, and long-term desirability of using the original components to construct new solutions.

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

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

The problem description is the area used to illustrate the application of this pattern.

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

A pattern is an effective way to solve a particular problem. A design pattern is not a library (a code base that can be included and used directly in your project), but rather a template for organizing your code. In fact, a code base and a design pattern have many different applications.

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

However, if there is nothing in the shop that suits you, you can create your own shirt (design its shape, choose the fabric, and then tailor it together). But if you are not a tailor, you may find it easy to find a suitable pattern and then follow this pattern to design your own shirt. With a model, you can get a skilled design shirt in less time.

Back to the discussion software, a data extraction layer or a CMS (Content management System) is a library-it's been designed and coded, and it's a good choice if it fits exactly what you need. But if you are reading this book, you may find that the inventory (original) solution does not always work for you. So far you know what you want, and you can achieve it, you just need a model to guide you.

The last idea: like a tailor's model, a design itself is useless. After all, you can't wear a costume model-it's just a piece of thin paper. Similarly, a software design model is just a guide. It must be designed according to the programming language and the characteristics and requirements of your application.

The goal of this book

The purpose of this book is not to comprehensively introduce the various types of software design patterns, nor to develop a new design pattern or terminology, but to highlight some of the well-known design patterns that are already in place. This book is unique in that it introduces some of the design patterns that I think are helpful for developing dynamic Web applications, and how these design patterns are implemented in the PHP language.

Oop in the face of object programming

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

If you are unfamiliar with OOP, there are a lot of related resources (books, websites, magazines, classes, etc.) to help you better understand it. Most OOP materials compliment its benefits-code reuse, code robustness, code encapsulation, polymorphism and extensibility-all of which are also important and useful. However, I think the main advantage of OOP is how it motivates you to break the problem down into manageable modules. Clear design and implementation, broken down into small modules so that your code can be more thoroughly tested and easier to understand and maintain.

Reader Skills Requirements

This book assumes that you are already able to use PHP fluently. In particular, this book assumes that you already understand the workings of PHP and PHP syntax and understand the fundamentals of using OOP to execute PHP code. This book is not an introductory book for PHP programming, nor is it intended to introduce the OOP programming of PHP.

Since not all OOP developers use the same terminology, I will define it in the body or in the 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 adopted by public groups. In my own work, I have started migrating new application development work to PHP5.0.3 environments, and so far I am pleased to find that PHP5 has good backward compatibility with PHP4 code, and that its object-facing model is one of the most significant new features of PHP5.

There are a number of good articles and instruction manuals to handle the nuances of the object model between different versions of PHP. But simply put, PHP5 offers:

The object handle will be explained below, and in more detail see chapter II: The value of the object model?

Better constructors (uniform name, not allowed to change)?

Destructor?

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

Exception handling (you can choose a new syntax try{}catch{} to trigger an error)?

Static class?

Image (Dynamic Check class, method, property)?

Type hidden?

PHP5 also offers some of the more obscure features:

A new Magic method?

__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 the serialization method

__tostring () allows you to control how a string is used to describe the object itself.

Auto-load autoloading (allows the user to load the class automatically when the class is first instantiated)?

Final (does not allow the method or a class to be overloaded with its subclasses)?

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 is no longer an implicit copy of the object, but instead provides an action handle.

To see the differences more clearly, let's 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 function Changeexample () is a copy of $obj, so this function does not change the value of $foo in the original object, so that the $obj->getfoo () final output is ' bar '.

In PHP5, because $obj is just an object handle in the function, the same changeexample () function actually affects the original object. In other words, with the action handle, it is no longer necessary to replicate 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

This problem becomes more complex when you use the $this variable in other objects or in the built-in constructor (__construct) of the object.

The result is that in PHP4, you almost always need:

Create a reference object, just like this $obj=?& new class;

Invoke the Reference object in the function, such as function func (?& $obj _param) {}

Capturing objects by referencing functions, such as function? &some_func () {} $return _obj=&some_funct ()

In fact, there are situations where you need to copy the original object. In my PHP4 code, I always make it clear that any unreferenced object task, such as copying a comment to an obvious object. In the long run, such a short note can greatly alleviate the headaches of anyone who maintains your code (the Translator notes: This code is maintainable). The knowledge of reference values, object handles, and object copying is explained in detail in chapter II, "Value of Object mode".

Although I am personally inclined to use PHP5 development, I feel that PHP4 will continue to be used by us for a considerable period of time, and that existing publicly released projects will continue to support PHP4. So, this book provides the same support for both versions of PHP. The instance code for PHP4,PHP5 Two versions is provided as much as possible. In each chapter, each block of code (modified in different versions of PHP) is provided with a corresponding comment indicating its change, such as//PHP4 and//PHP5.

Bibliography and other resources

Here are a number of relevant reference books to help you better learn the design patterns. The design pattern of the Bible (translator: The best book) is Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides (his pioneering works are often referred to as "Gang of four" shorthand for "GOF", is to represent them four people) wrote the "design pattern: Reusable software development principles for the face of the object."

On "design mode", the next most useful book on PHP Web application design Patterns is Martin Fowler published by Patterns of Enterprise application Architecture (Translator: Enterprise Application architecture model). Compared with Gof's book, which contains all the general design patterns, Fowler's book details many of the design patterns that are specifically designed to develop Web applications.

There is also a wealth of resources available on many websites about design patterns, and a particularly typical site is the Portland Model Library (http://cz.com/por/).

Another site about PHP design mode is phppatterns, the online address is http://www.phppatterns.com.

Thank

I am grateful to my boss, who, in his place, my duties and responsibilities allow me to spend some of my time in this area of interest and to thank him for providing me with the knowledge and experience that I am confident of finishing this book.

Another source of my inspiration, ideas and experience is the forum SitePoint this site (http://www.sitepoint.com). In particular, contributors who regularly "Advanced PHP Forum" (Translator: PHP high-level forums) have a wealth of knowledge and experience, which is the most generous group I have found on the internet to share my ideas. It is through these resources (translator Note: SitePoint site) that I landed SimpleTest (http://simpletest.sf.net), Wact (http://wact.sf.net) and many other PHP projects that I consider invaluable. In the years that followed, I wanted SitePoint to continue to be a rich resource point for PHP developers.

Without the contributions and important efforts of the PHP development team, this book is clearly impossible to exist. Because they have developed a language that is so useful, easy to learn, versatile, and well suited for developing Web applications.

Finally, I would like to thank all the members of Marco Tabini and Php|architect. This magazine (Translator Note: Php|architect) has become a source of many different PHP themes, and these topics are published by professional developers. The meetings organized by macro and company are also quite good.

The above is PHP Tutorial: PHP design mode before the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

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