Archive for the 'Design Patterns' Category

PHP Proxy Design Pattern: Protect Your Assets

Protection Proxy Design Pattern

The Proxy Design Pattern is another pattern that’s easy to understand. Essentially, you have a proxy object that acts as a stand-in for a real object. A request is made to the Proxy which in turn passes on the request to the RealSubject or blocks the request from the RealSubject. The purpose of the Proxy is to have variation where you have different ways an object is accessed. As a result, you find the Proxy patterns are commonly found where you have login controlled by a username and password. The access, while it may appear to be directly to the object of interest, is actually through a proxy object.

Try it out clicking the Play button and the Download button will download all of the files. (To figure out the username and password see the Proxy.php file listing.)

The Many Faces of Proxy

The Proxy design pattern has more than one kind. All Proxy designs separate the request from the RealSubject, but because of the different applications, Gamma, Helm, Johnson and Vlissides (p. 210) specify three distinct kinds of proxies:

  1. Remote Proxy. When a proxy object is in one address space and the real object is in another, the proxy is a remote one. Besides using a remote proxy as a firewall, the remote proxy can be used for online games where the same object is needed in different places at the same time.
  2. Virtual Proxy. A virtual proxy may cache information about a real subject so that access to the real subject can be postponed. Sometimes high security logins use a virtual proxy for the login before the real object handles the login data.
  3. Protection Proxy. The protection proxy keeps the request away from the real subject until the request is verified by the protection proxy. The real subject is the target of the request, such as access to database information. Many protection proxies have different levels of access, depending on the user’s login information; so instead of having a single real subject, the real subject may be multiple and restricted.
  4. Figure 1 shows the proxy’s structure that can be applied to all three kinds of proxies:

    Figure 1: Proxy Design Pattern

    The RealSubject and Proxy classes share the same interface (Subject) whether it is an abstract class or interface. Note that the request is through the Subject interface, and with PHP, that can be a little tricky, but as you’ll see, not impossible.

    Ask the Proxy

    To understand the Proxy design pattern In a nutshell,

    The client makes a request through the proxy and the proxy passes on the request to the real subject.

    Often, you will see an object diagram that outlines the structure of the pattern at run-time. Figure 2 shows the Proxy pattern in such a diagram:

    Figure 2: Proxy Object Diagram

    As you can see, the client holds a reference to the Subject and the Proxy holds a reference to the RealSubject. In designing an application in PHP, we need to keep in mind that the reference to an interface requires use of PHP type hinting. That is a crucial requirement because programming to an interface instead of an implementation is one of the key requirements of using design patterns correctly. The interfaces provide the loose coupling in a design pattern.
    Continue reading ‘PHP Proxy Design Pattern: Protect Your Assets’

Share

PHP Factory Method Design Pattern : Decoupling Your Products

Let the Factory Build Your Products

One of the easiest design patterns to both understand and create is the Factory Method. However, the Gang of Four provide more than a single basic structure for the pattern and do not specify exactly where the Client makes its request. As a result, one may not recognize one implementation or another. Generally, I assume that requests from the Client class are made directly through the Creator class. However, some implementations suggest that the Client holds a reference to both the Creator and Product (GoF, 110). For this example I chose to use a parameterized version. In this version of the Factory Method pattern, the factory method is allowed to create multiple kinds of products. As noted by GoF,

The factory method takes a parameter that identifies the kind of object to create. All objects the factory method creates will share the Product interface.(pp. 110-111).

This approach calls for an abstract class that can handle a wide variety of concrete products. At the same time, though, we want it to be useful as well. For this example, the Product class has an abstract method to generate the concrete product (getData), but it also holds the properties with the connection values for the MySQL server. So this allows the developer to change the contents of the concrete products without having to even think about the connection values. (This assumes that the same connection information is used by all of the products.) Figure 1 shows the class diagram for this kind of Factory Method implementation.

Figure 1: Parameterized Factory Method Class Diagram

The Client’s role is implied to hold references to the Creator class (factory) and the Product class. The Product reference is through a parameter in the Creator instance. Because the the Creator interface holds a Product as its parameter in the form of a type hint, the request from the Client is to the abstract Product class and not the concrete product declared in the ConcreteCreator parameter. As a result, it’s easy to add more concrete products without having to re-write the whole program. You can just add the new concrete product class with the appropriate interfaces and call them with the Client referencing the concrete product as a parameter of the ConcreteCreator instance. For instance, the following lines shows such a request:

$this->graphicGetter=new ConcreteCreator();
print($this->graphicGetter->factoryMethod(new GraphicProduct()));

The same instance could be called again for a TextProduct. Therein lies the beauty of programming to the interface instead of the implementation. You can test the program and download the files by clicking the buttons below.

Note: When you look at the code in the downloaded files or in the listings, I used the MySQL settings from my localhost on my computer. Obviously, you will want to substitute those settings for your own; so be sure to get your own MySQL user, password, databases and tables set up before trying to run the files. Also, the project stemmed from a Dreamweaver PHP group whose names were substituted by known and unknown blues, boogie and jazz artists. Make changes in those elements to suit your tastes.

To better understand the actual program, click below to go to the steps in building the application:

Continue reading ‘PHP Factory Method Design Pattern : Decoupling Your Products’

Share

PHP Decorator Design Pattern: Accessorizing Your Classes

decorator design pattern

Decorating an Object

Adding Just the Flourishes You Need

How would your like your concrete classes to be like an unadorned Christmas tree? When you need an ornament, you put it on. You can put on several of the same type, all different types and when they’re no longer needed, you can take them off. Your central object (class) is unchanged and you’re not processing stuff you’re not using. When you need it; you just pop it on like an ornament on a tree. Further, you can decorate different components with the same ornaments.

When would you use such a pattern? Consider setting up an order form. Each order is an object, and you decorate your order with other objects the user wants to buy. When I buy a computer, I accessorize it with with added memory, a Webcam, a USB hub and anything else that I think I need. However, the store doesn’t have to have a separate computer for every possible combination that users may want to buy. They can just have a few and let the user decorate them anyway she wants. Further, the object you want does not have to drag every option with it—just the ones the buyer wants. You can play the test case and download all of the files using the following two buttons:

The Structure

To kick things off, let’s take a look at the class diagram that the Gang of Four devised. It is one of the most interesting because an abstract class is subclassed from another abstract class (among other things) as can be seen in Figure 1:

Figure 1:Decorator Class Diagram

In looking at what varies, we find that the variation is responsibilities of an object without sub-classing—in other words, use delegation. However, you can see that both the Decorator class and the Concrete Components and Decorators are all sub-classed from Abstract classes. Isn’t that inheritance instead of composition? Of all of the things that can vary in a program structure, those assigned to the Decorator still need further clarification. As you will see in the next section, the Decorator seems to even contradict its own element of variation because it double-subclasses. However, once everything is straightened out, you will find the Decorator example we use to be very simple to implement and even use in a real live work situation.
Continue reading ‘PHP Decorator Design Pattern: Accessorizing Your Classes’

Share

Why Are PHP Design Patterns Missing Pieces?

Why are Participants Missing? The Case of the Missing Participants

Recently I was working on a Decorator pattern and struggling through PHP’s way of doing things. So naturally I thought why not take a look at how others have solved these same problems. The Gang of Four refer to the different classes and interfaces that make up a design pattern, as participants, and when I look at a design pattern, the first thing I do is to see how the developer handles the different participants. What I found was surprising—they left out chunks of a design pattern in their examples. Alternatively, they just did some kind of workaround that effectively made it work (run), but it was no longer a design pattern or had the advantages of a design pattern.

The Strategy with the Missing Context

The Strategy pattern decouples the algorithms from the Client by using a Context class. All of the requests for the algorithms (found in concrete Strategy classes) go through the Context to the Strategy interface and on the the implemented strategies in the form of concrete classes. However, in many of the PHP examples, they leave out the Context class and Strategy interface and go directly from an Object to concrete Strategies. In several examples, the code authors chose to ignore the interfaces and even the abstract classes and have fairly direct connections between concrete strategies and some kind of object. Figure 1 shows the kinds of UMLs that accompany these kinds of PHP design pattern implementations—if indeed they are implementations.

Figure 1: Minimalist UML

You can see clearly that the UML in Figure 1 has little in common with the class diagram we used that was an exact replica of the Strategy pattern that the Gang of Four used.

The authors of this kind of “explanation” of the Strategy pattern seem to think that the separation of the algorithms from the object is a matter of nothing more than taking the algorithms out of some object and using them independently of the main object. However, while that is an improvement on cramming everything into a single object (class), it is not a design pattern. Yes, it does add flexibility because more than one class can use the same concrete strategies. So, it’s a step away from single-class programming and even procedural programming. However, it is not a design pattern and it does not have the design pattern’s flexibility. The Context class uncouples the request from the strategy and without it, that concrete strategies are tightly linked to the “object”—whatever that may be.
Continue reading ‘Why Are PHP Design Patterns Missing Pieces?’

Share

PHP Strategy Design Pattern: Encapsulating Algorithms

Strategy Design PatternOne of the most useful design patterns is the Strategy pattern. Where variation in algorithm use is key, the Strategy pattern encapsulates the algorithms and uses delegation to handle requests. You can easily change algorithms by re-writing the code just for the algorithm. Adding algorithms is just as easy when the requirements for your application change because all of the code for the algorithm is encapsulated in separate objects (classes). So instead of having your algorithms scattered all over the place, the Strategy pattern organizes and encapsulates them.

To get started, take a look at the class diagram for the Strategy pattern. If you are familiar with the State design pattern, you’ll see that the class diagrams are identical, but do not assume that the patterns are the same because they are very different. When we discuss the State pattern, we’ll look at those differences, but for now, just focus on the Strategy pattern itself.

Figure 1: Strategy class diagram

All requests from the Client (not shown in the diagram) go through the Context class to the Concrete Strategies through the Strategy interface.

Before continuing you need to know that not only do design patterns use a lot of classes, but they are typically saved in separate files. When it comes time to update and re-use materials, this arrangement works quite well. Further, you have to place all of the files in the same directory—this was done to keep it simple, but feel free to change that into multiple directories and re-code the materials so that the links are updated. Save some time by downloading all the code and get an idea of what the program does by clicking on the appropriate button below:

Algorithm Writers’ Heaven

I’ve never met two PHP programmers who agree on the same algorithm for…well just about anything. This is the beauty of the Strategy design pattern. All of the algorithms are encapsulated, and so if you don’t like the algorithms, you can change them to suit your own style and wisdom. Further, if you decide to add functionality to a program or to change the functionality, you can simply change one of the algorithms without the whole house come crashing down around your ears. Of course the Strategy pattern was not designed for cantankerous PHP programmers who don’t like other’s algorithms but rather for programmers who have to deal with changing functionality in an application or several different algorithms from the same “family.” In effect, you set up an interchangeable set of algorithms by establishing an interface with the desired method(s) and control the whole operation through a context class.

The algorithms can vary independent of the client (Client class) who uses it. Further, the strategies eliminate the need for conditional statement. Instead of using a conditional to call a different algorithm, the strategies are encapsulated in separate classes (implementations of a strategy interface), and so they can be called directly by the client through the context.

What’s Wrong with Conditional Statements?

Let me just blurt it out :

I avoid conditional statements whenever possible.

Such a claim may seem to be a little odd since the Chain of Responsibility pattern uses them extensively. The handleRequest() method in all of the concrete Handler classes use conditional statements. That’s true, but the conditionals are all the same and only check to see whether the request can be handled by the current concrete handler or not. These operations are little checkers or inspectors that either handle to request or pass it along the chain. They’re not the kind that have to think about several alternatives.
Continue reading ‘PHP Strategy Design Pattern: Encapsulating Algorithms’

Share