Home > Backend Development > PHP Tutorial > PHP Tutorial: Preface to PHP Design Patterns

PHP Tutorial: Preface to PHP Design Patterns

黄舟
Release: 2023-03-04 08:30:01
Original
1135 people have browsed it

When you are constantly trying to discover new features from your applications, do you find that the solutions you propose are so similar to some things you have implemented before? If you're a programmer (even if you've only been starting out for a short time), you probably answered "yes." It looks like you are using some old code to solve newly discovered problems during software development. You may have realized that your solution is fundamental, a method that can be widely repeated not just by you but by all professional developers.

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

History of Design Patterns

The term “design pattern” was originally coined 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 this collection of existing, well-known patterns to start new and effective designs. . Alexander's perspective translates well to software development, and there is a long-term consensus on using existing components to construct new solutions.

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

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

The problem description is used to illustrate the application field of this model. ?

Solution describes the execution of this model. A good discussion of a design pattern should cover the advantages and disadvantages of using the model.

A pattern is an effective way to solve a specific problem. A design pattern is not a library (a library of code that can be included and used directly in your project) but a template for organizing your code. In fact, there are many differences in the application of a code base and a design pattern.

For example, a shirt you buy from a store is a code library. 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, then you can create your own shirt (design its shape, choose the fabric, and tailor it together). But if you are not a tailor, you may find it easy to find a suitable pattern and then design your own shirt according to this pattern. Using a mockup, you can get a proficiently designed shirt in less time.

Back to discussing software, a data extraction layer or a CMS (content management system) is a library - it has been designed and coded before, if it meets your needs accurately then it is a library Good choice. But if you're reading this, you may have discovered that stock solutions don't always work for you. Now that you know what you want, and you can achieve it, you just need a model to guide you.

One last thought: Just like a tailoring model, a design is of little use on its own. After all, you can't wear a model of clothing - it's just pieced together from 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.

The goal of this book

The purpose of this book is not to comprehensively introduce various categories of software design patterns, nor to develop a new design pattern or terminology, but to highlight some existing well-known design patterns. . What makes this book unique is that it introduces some design patterns that I think are helpful in 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 viewpoints are based on OOP, a very natural design pattern, and are implemented using OOP.

If you are not familiar with OOP, there are many related resources (books, websites, magazines, classes, etc.) to help you understand it better. Most OOP literature extols its benefits - code reuse, code robustness, code encapsulation, polymorphism and extensibility, all of which are also very important and useful. However, I think the main advantage of OOP is how it encourages you to break down problems into tractable modules by yourself. Clear design and implementation, broken down into smaller modules, will allow your code to be more thoroughly tested and easier to understand and maintain.

Reader skill requirements

This book assumes that you are already able to use PHP fluently. In particular, this book assumes that you already have a working knowledge of PHP and PHP syntax and understand the basic principles of executing PHP code using OOP. This book is not an introduction to PHP programming, nor is it intended to introduce OOP programming in PHP.

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

PHP4 and PHP5

When I write this book, PHP5 has been released for some time, but has not yet been widely adopted by the public community. In my own work, I have started migrating new application development work to the PHP5.0.3 environment, and so far I am happy to find that PHP5 has good backward compatibility with PHP4 code, and at the same time Its object-oriented model is one of the most significant new features of PHP5.

There are a lot of good articles and guides out there that deal with the subtle differences between object models between different PHP versions. But in simple terms, PHP5 provides:

Object handles (will be explained below, see Chapter 2: The Value of the Object Model for more details)?

Better constructors (unified names, no changes allowed)?

Destructor?

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

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

Static class

Imaging (dynamic checking of classes, methods, properties)

Type hiding?

PHP5 also offers some more obscure features:

New magic methods

__get() and __set() allow you To control variable access

__call() allows you to dynamically intercept all attributes of the called object.

__sleep() and __wakeup() allow you to overload serialization methods

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

Autoloading (allows the user to automatically load the class when it is objected for the first time)?

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

Object handle

PHP5 The best feature is to use handles to define classes, similar to a file or database handle. Using an object in a PHP function no longer implicitly copies the object, but provides an operation handle.

To see the difference 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 the function changeExample() is a copy of $obj, so this function does not change the original object The value of $foo, so that the final output of $obj->getFoo() is 'bar'.

In PHP5, since $obj is just an object handle in the function, the same changeExample() function really affects the original object. In other words, using handles, there is no need to copy 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 will become more serious when you use the $this variable in other objects or the built-in constructor (__construct) of this object. complex.

It turns out that in PHP4, you almost always need to:

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

Call the reference object in a function, like function func(?&$obj_param){ }

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

In fact, there are now cases where you also need to copy the original object. In my PHP4 code, I always comment clearly any non-referenced object tasks such as copying an explicit object. In the long run, such a short comment can greatly reduce the headache of anyone maintaining your code (Translator's Note: Such code is very maintainable). The related knowledge of reference passing by value, object handle and object copy will be explained in detail in Chapter 2 "The Value of Object Pattern".

Although I personally prefer to use PHP5 for development, I feel that PHP4 will continue to be used by us for quite a long time, and existing publicly released projects will continue to support PHP4. Therefore, this book provides the same support for both versions of PHP. Example codes for both versions of PHP4 and PHP5 are provided as much as possible. In each chapter, each code block (which has been changed in different PHP versions) is provided with corresponding comments to indicate the changes, such as //php4 and //php5.

Bibliography and other resources

There are many related reference books here to help you learn design patterns better. The "Bibles" (translator's translation: the best books) of design patterns are Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (whose seminal work is often referred to as the "Gang of Four" abbreviated as "GOF"). It is "Design Patterns: Principles of Reusable Object-Oriented Software Development" written on behalf of four of them).

Regarding "Design Patterns", the next most useful book on PHP WEB application design patterns is Patterns of Enterprise Application Architecture (Translator's Translation: Enterprise Application Architecture Model) published by Martin Fowler. While GOF's book contains all general design patterns, Fowler's book introduces many design patterns specifically for developing web applications in detail.

In addition, many websites also provide rich resources on design patterns. A particularly typical website is the Portland Model Library (http://cz.com/por/).

Another website about PHP design patterns is phpPatterns, and the online address is http://www.phppatterns.com.

Thank you

I am very grateful to my boss, where my tasks and responsibilities allow me to spend part of my time in this field of interest to me. I am also grateful to him for providing me with the knowledge and experience that gave me the confidence to finish writing this. book.

Another source of inspiration, ideas and experience for me is the forum on SitePoint (http://www.sitepoint.com). In particular, the contributors who regularly go to the Advanced PHP Forum have a wealth of knowledge and experience and are the most generous group of people sharing their ideas that I have found online. . It is through these resources (Translator's Note: SitePoint site) that I logged into SimpleTest (http://simpletest.sf.net), WACT (http://wact.sf.net) and many others that I think are priceless. PHP project. In the years to come, I hope SitePoint will continue to be a rich resource for PHP developers.

This book obviously would not be possible without the contributions and significant efforts of the PHP development team. Because it is they who developed such a language that is easy to use, easy to learn, versatile and very suitable for developing WEB applications.

Finally, I would like to thank Marco Tabini and all the members of php|architect. This magazine (Translator's Note: php|architect) has become the source of many different PHP themes, and these themes are published by professional developers. The conferences hosted by Macro and company were also pretty good.

The above is the content of the preface of PHP Tutorial: PHP Design Patterns. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template