Medium 9781449344917

Learning PHP Design Patterns

Views: 966
Ratings: (0)

Build server-side applications more efficiently—and improve your PHP programming skills in the process—by learning how to use design patterns in your code. This book shows you how to apply several object-oriented patterns through simple examples, and demonstrates many of them in full-fledged working applications.

Learn how these reusable patterns help you solve complex problems, organize object-oriented code, and revise a big project by only changing small parts. With Learning PHP Design Patterns, you’ll learn how to adopt a more sophisticated programming style and dramatically reduce development time.

  • Learn design pattern concepts, including how to select patterns to handle specific problems
  • Get an overview of object-oriented programming concepts such as composition, encapsulation, polymorphism, and inheritance
  • Apply creational design patterns to create pages dynamically, using a factory method instead of direct instantiation
  • Make changes to existing objects or structure without having to change the original code, using structural design patterns
  • Use behavioral patterns to help objects work together to perform tasks
  • Interact with MySQL, using behavioral patterns such as Proxy and Chain of Responsibility
  • Explore ways to use PHP’s built-in design pattern interfaces

List price: $33.99

Your Price: $27.19

You Save: 20%


14 Slices

Format Buy Remix

1. PHP and Object-Oriented Programming


All the forces in the world are not so powerful as an idea whose time has come.

Do not pray for tasks equal to your powers. Pray for powers equal to your tasks.

Immense power is acquired by assuring yourself in your secret reveries that you were born to control affairs.

Ignorance is the curse of God; knowledge is the wing wherewith we fly to heaven.

When we first learn to read, the stories, vocabularies, and words tend to be small and simple. Dealing with small and simple stories requires small and simple tools. However, when we are more advanced and introduced to the works of William Shakespeare, we need a more complex, larger, and more sophisticated toolset. If a kindergarten teacher handed her brood Hamlet, chances are the kids wouldnt understand it, but if they are given an incremental set of reading tools over the years, by the time they reach high school, they can read, understand, and appreciate Hamlet. This book is for developers who are ready to read the PHP version of Hamlet.


2. Basic Concepts in OOP


Two elements are needed to form a trutha fact and an abstraction.

Beware how you trifle with your marvelous inheritance, this great land of ordered liberty, for if we stumble and fall, freedom and civilization everywhere will go down in ruin.

Everybody gets everything handed to them. The rich inherit it. I dont mean just inheritance of money. I mean what people take for granted among the middle and upper classes, which is nepotism, the old-boy network.

Our normal waking consciousness, rational consciousness as we call it, is but one special type of consciousness, whilst all about it, parted from it by the filmiest of screens, there lie potential forms of consciousness entirely different.

If youre new to OOP, dont expect everything to make sense right away. As you use OOP more and more, youll experience little aha! moments when the pieces begin to come together. PHP does have important OOP features, and it has its own way of implementing these features in the language. If you are familiar with other OOP languages, you can be assured that PHP is different in placeslike allowing constants to be a part of an interface. Understanding abstraction is a cornerstone in both OOP and design patterns, and the more you use it, the more sense it makes.


3. Basic Design Pattern Concepts


Large organization is loose organization. Nay, it would be almost as true to say that organization is always disorganization.

If you only have a hammer, you tend to see every problem as a nail.

Because things are the way they are, things will not stay the way they are.

Way back in the 1970s when user interfaces (UIs) were fairly primitive, a programmer decided to separate key elements of what was required in a graphical user interface (GUI). Each of the parts was given a specific task, and each part communicated with the other parts. The parts were grouped into domain objects and presentation objects. The domain objects were for modeling what perception the user was given of the real world, and the presentation objects were what was viewed on the screen. The parts were divided into a model, a view, and a controller, and the Model-View-Control (MVC) design pattern came into being.

The domain element in the MVC is the model. The model is responsible for what is variously called the data, business, or application logic. For example, take a thermostat. Within the thermostat is a value that represents a temperature, either the actual ambient temperature or a value where a heater is turned Off or On. Somewhere in that thermostat you have a set of data that can be envisioned as set into variables:


4. Using UMLs with Design Patterns


Reality seems valueless by comparison with the dreams of fevered imaginations; reality is therefore abandoned.

The earliest phase of social formations found in historical as well as in contemporary social structures is this: a relatively small circle firmly closed against neighboring, strange, or in some way antagonistic circles.

Neither the life of an individual nor the history of a society can be understood without understanding both.

In their book, Design Patterns: Elements of Reusable Object-Oriented Software, Gamma, Helm, Johnson, and Vlissides (Addison-Wesley) employ a UML that may have slight variations from 1990s era UML standards, as well as contemporary UML 2.0 standards. However, those variations are slight, and by employing the GoF version of a UML, the reader will be able to compare the design patterns using PHP in this book with the Gang of Fours original work. So whatever arguments may exist about the best UML for programming, you will find strict consistency between the UML in this book and the original work by Gamma and his associates.


5. Factory Method Design Pattern


Womens movements would form among the factory workers, a great mobilisation that destroyed the old models.

Design is the method of putting form and content together. Design, just as art, has multiple definitions; there is no single definition. Design can be art. Design can be aesthetics. Design is so simple, thats why it is so complicated.

Create your own method. Dont depend slavishly on mine. Make up something that will work for you! But keep breaking traditions, I beg you.

As part of the creational category of design patterns, the Factory Method pattern is involved with creating something. In the case of the Factory Method, the something created is a product that is not tied to the class that creates it. Instead, in order to maintain loose coupling, the client makes the request through a factory. The factory then makes the requested product. Another way of thinking about it is that the Factory Method frees the product from the requestor. Figure5-1 shows a class diagram of the Factory Method.


6. Prototype Design Pattern


Originality is nothing but judicious imitation. The most original writers borrowed one from another.

We forfeit three-quarters of ourselves in order to be like other people.

Act that your principle of action might safely be made a law for the whole world.

The Prototype design pattern is interesting in its use of a cloning technique to replicate instantiated objects. New objects are created by copying prototypical instances. In this context, instances refer to instantiated concrete classes. The purpose is to reduce the cost of instantiating objects by using cloning. Rather than instantiating new objects from a class, a clone of an existing instance can be used instead. Figure6-1 shows the Prototype class diagram.

Figure6-1.Prototype class diagram

Note that the Client class is an integral part of the Prototype design pattern. The client creates an instance of a concrete prototype through the Prototype interface that includes a clone method of some sort. Fortunately, PHP has a built-in clone() method that can be used within the design pattern. As you will see, the basics of the design are quite simple.


7. The Adapter Pattern


It is not the strongest of the species that survives, nor the most intelligent that survives. It is the one that is the most adaptable to change.

The measure of intelligence is the ability to change.

Science always has its origin in the adaptation of thought to some definite field of experience.

This chapter is a two-for-one package: object and class Adapters. This chapter has many lessons, but one of the most interesting is seeing the difference between using inheritance and using composition. The class scope version of the Adapter design pattern uses inheritance, as can be seen in the class diagram in Figure7-1.

Figure7-1.Adapter class diagram using inheritance

In the class diagram, one implementation of the pattern is to have one class with dual inheritance. As you will see, dual inheritance is not allowed in PHP 5, but there are alternatives to dual inheritance where the pattern can be correctly implemented with a combination of inheritance and implementation.


8. Decorator Design Pattern


Charm, in most men and nearly all women, is a decoration.

This wasnt just plain terrible, this was fancy terrible. This was terrible with raisins in it.

The ornament of a house is the friends who frequent it.

She well knew the great architectural secret of decorating her constructions, and never condescended to construct a decoration.

As a structural pattern, the Decorator adds to an existing structure. With the Adapter pattern, the addition to an existing structure is by adding an adapter class that resolves incompatible interfaces. The Decorator adds objects to existing objects. Also called wrapper (as was also the Adapter), the Decorator participant wraps the Component participant with concrete components. Figure8-1 shows the class diagram, but before going over it, several details need to be considered.

First of all, the Decorator is one of the few design patterns that includes one abstract class inheriting another abstract class. As you can see in Figure8-1, a looping aggregation connects the Decorator to the Component participant. (The looping line looks more like wrapping than the straight line used in the original Gang of Fours class diagramsee also the Freemans Head First Design Patterns, page 91.) The Decorator can be said to wrap the Component.


9. The Template Method Pattern


It is easy to study the rules of overloading and of templates without noticing that together they are one of the keys to elegant and efficient type-safe containers.

All the great legends are Templates for human behavior. I would define a myth as a story that has survived.

I work out the other bits, too, but I need to know what I look like, very early on. And then its like a template; Ill fill that person out. If I get that out of the way, then Im all right.

First of all, you need to differentiate between the Template Method as a design pattern and the templateMethod()a class methodused within a Template Method pattern. The templateMethod() is a concrete method within an abstract class. It orders the sequence of abstract methods, leaving the implementations up to a concrete class. At its core, the Template Method defines the skeleton of an algorithm in an operation while the exact implementations are left up to the concrete classes.

The good thing about the Template Method is that it is relatively small and easy to implement. A single abstract and concrete class is all you need, as shown in Figure9-1.


10. The State Design Pattern


Could the young but realize how soon they will become mere walking bundles of habits, they would give more heed to their conduct while in the plastic state.

In each action we must look beyond the action at our past, present, and future state, and at others whom it affects, and see the relations of all those things. And then we shall be very cautious.

All our final decisions are made in a state of mind that is not going to last.

The State design pattern is one of the most intriguing and useful patterns of those devised by GoF. Games often depend on the State pattern because objects can change states so frequently in games. The purpose of the State pattern is to allow an object to change its behavior when the state changes. Many other simulations, whether they are games or not, depend on the State pattern as well; you will find many uses for it, as this chapter demonstrates. Figure10-1 shows the basic design pattern in a class diagram.

Figure10-1.State design pattern class diagram


11. A Universal Class for Connections and a Proxy Pattern for Security


It is art that makes life, makes interest, makes importance... and I know of no substitute whatever for the force and beauty of its process.

Substitute damn every time youre inclined to write very; your editor will delete it and the writing will be just as it should be.

The work of science is to substitute facts for appearances, and demonstrations for impressions.

In Chapter2, you saw one example of how PHP allows interfaces to store constants that can be used by classes that implement the interface. One set of constants that can be stored in the interface is that required for connecting to a MySQL database. The routine using the PHP mysqli extension provides some variations for connection, but all variations need the host, username, password, and database information. Once the routine is set in a class, it should be available for general reuse whenever a program requires a MySQL connection. Figure11-1 shows the class diagram for this arrangement.


12. The Flexibility of the Strategy Design Pattern


Victorious warriors win first and then go to war, while defeated warriors go to war first and then seek to win.

In preparing for battle I have always found that plans are useless, but planning is indispensable.

All I had done was to improve on their strategy, and it was the beginning of a very important lesson in lifethat anytime you find someone more successful than you are, especially when youre both engaged in the same businessyou know theyre doing something that you arent.

One of the ongoing tasks in using PHP with MySQL is writing algorithms for the different kinds of requests made of a MySQL application. Typical requests include creating tables or entering, selecting, changing, and deleting data. The algorithms for these different requests are simple or complex depending on both the complexity of the request and of the table.

One of the main principles of design patterns is to encapsulate what varies. With several different algorithms for different kinds of requests sent to a PHP class that handles these MySQL requests, the variation is clearly the algorithms. The variations may be small or great, but using the Strategy design pattern, we can greatly simplify the process.


13. The Chain of Responsibility Design Pattern


Most people do not really want freedom, because freedom involves responsibility, and most people are frightened of responsibility.

We are made wise not by the recollection of our past, but by the responsibility for our future.

By imposing too great a responsibility, or rather, all responsibility, on yourself, you crush yourself.

The buck stops here.

The Chain of Responsibility design pattern separates the sender of a request from the receiver. This avoids coupling of the requester and receiver. Further, the pattern allows a request to be passed along a chain to several different objects that have an opportunity to handle the request. The sender doesnt need to know which object handles the request, and the object doesnt need to know who sent the request. Theres no coupling between the two.

The advantages of the Chain of Responsibility is that any object can send the request to the objects that handle it, and the objects that handle a request can be changed so that more or different objects can be incorporated to deal with requests. So changes can be made in both the requester and request handlers without disrupting a larger system. Figure13-1 shows the class diagram for the Chain of Responsibility pattern.


14. Building a Multidevice CMS with the Observer Pattern


If there were observers on Mars, they would probably be amazed that we have survived this long.

In dream consciousness... we make things happen by wishing them, because we are not only the observer of what we experience but also the creator.

Knowledge is what we get when an observer, preferably a scientifically trained observer, provides us with a copy of reality that we can all recognize.

One of the many treats found within PHP 5.1.0 and up is a set of interfaces that can be used with the Observer design pattern. This chapter will look at an Observer pattern beginning from scratch without any built-in features, but to get started well have a short overview of the SplObserver interface along with the SplSubject and the SplObjectStorage interfaces that make building an Observer pattern with PHP a snap. SPL is shorthand for Standard PHP Library and consists of a collection of interfaces and classes used to solve standard problems.

However, before we get ahead of ourselves, you need some idea of what the Observer pattern is and what it does. Fortunately, its class diagram is quite detailed, and many of the features prized in the Model-View-Controller (MVC) pattern can be found in the Observer. (You might even think of the pattern as an alternative to the MVC.) At the root of the Observer are Subject and Observer interfaces. The Subject holds a given state and the observers subscribe to the subject to be informed of the current state. You can think of it as a blog with many subscribersone set of information is routinely updated for a variety of users who subscribe or regularly read the blog. Each time the blog is changed (its state changes), all of the subscribers are informed. Figure14-1 shows the Observer class diagram.



Print Book

Format name
File size
0 Bytes
Not Allowed
Not Allowed
Read aloud
Format name
Read aloud
In metadata
In metadata
File size
In metadata