ARE Design Patterns portable from one language to another? Of course they are. I’ve read some accounts that claim otherwise, but I’ve not found any design pattern that could not be used in any computer language that I’ve tried. (Maybe I’m just conversant in languages where design patterns do work, but I don’t think so.) Anyway, Chandima and I have been discussing doing a set of PHP design patterns, and I wanted one for a contact form I had done using PHP.
For this blog, though, I thought I’d use a translation from one of the design patterns we have on this blog so that you can more easily see the similarities and differences between ActionScript 3.0 and PHP in implementing the same design pattern.
Chain of Responsibility
As you may recall from our Chain Of Responsibility (CoR) post, the design pattern is used when you want to have a system that takes care of requests when you have different outcomes. In our original example, we added a helper class called Request, but otherwise we stuck with the basics of the CoR structure. Figure 1 shows the class diagram of the CoR we used in our initial post.

Figure 1: Chain of Responsibility Class Diagram
In this particular design pattern the Client class is a full-fledged participant in the pattern. Because Client classes are request objects themselves, it may seem odd to have a Request class. Just think of the Request class as a helper class that encapsulates requests for the Client.
The back story to this CoR implementation is that you have a company that needs to distribute pick-up trucks using the minimum size truck for any given load. So, you set up a CoR design to check the load requirements sent in, and then dispatch the smallest possible truck for a given load. (For other details of the CoR and ActionScript 3.0, check out the original CoR post.)
The PHP implementation of CoR
Assuming you’ve looked at the original CoR post, let’s jump right in to the PHP implementation. Figure 1 shows the exact same set of classes that we’ll use with the PHP version of the design. We’ll start at the heart of the CoR with the Handler class. PHP has true abstract classes and we can create the Handler using an abstract class. (In case you’re wondering, we probably could have done the same thing with an interface, but tweaking seems easier using abstract classes.)
1 2 3 4 5 6 7 8 9 | <?php abstract class Handler { abstract public function handleRequest($request); abstract public function setSuccessor($nextTruck); } ?> |
The handleRequest() method uses an encapsulated request from the Request class that is instantiated in the Client. As you can see, PHP does not have strong typing; so the parameters are not typed. The setSuccessor() establishes the next link in the chain. If the current object (class) cannot provide what is requested, the request is passed to the successor.
For this example, three concrete Handler objects—GMC, Dodge and Ford—handle all requests. If a load is too heavy for the lightest truck, the request is passed on to the next one and so on until the request reaches the end of the chain. For this example, there’s no “too heavy” notice if the load surpasses the capacity of the largest truck, but it’d be easy to add such a notice or another class that provides remedies for loads too heavy for the largest truck. (In case you’re considering a solution, think modulo.)
The Concrete Handlers
The three concrete handlers represent the load capacities of three trucks. Each concrete handler looks at the load and if it can handle it, it says so. Otherwise, it passes the request up the line until it reaches the end of the chain or a truck with in the load parameters. The following three classes represent concrete handlers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | <?php //GMC Class class GMC extends Handler { private $successor; public function setSuccessor($nextTruck) { $this->successor=$nextTruck; } public function handleRequest ($request) { if ($request->getPounds() < 1547) { echo ("A GMC Canyon would be good for this. Weight: " . $request->getPounds() . "<br />"); } else if ($this->successor != NULL) { $this->successor->handleRequest ($request); } } } ?> //Dodge class <?php class Dodge extends Handler { private $successor; public function setSuccessor($nextTruck) { $this->successor=$nextTruck; } public function handleRequest($request) { if ($request->getPounds() < 1750) { echo "A Dodge Dakota can handle this load. Weight: " . $request->getPounds() . "<br />"; } else if ($this->successor != NULL) { $this->successor->handleRequest($request); } } } ?> //Ford class <?php class Ford extends Handler { private $successor; public function setSuccessor($nextTruck) { $this->successor=$nextTruck; } public function handleRequest ($request) { if ($request->getPounds() < 1890) { echo ("This load requires a Ford 150. Weight: " . $request->getPounds() . "<br />"); } else if ($this->successor != NULL) { $this->successor->handleRequest ($request); } } } ?> |
As you can see, each link in the chain (concrete Handler class) uses a simple conditional statement to handle the request. The “handling” is merely using an echo statement to announce that a particular truck can handle the load. (In this case the Ford may be hopelessly unrealistic, but never mind.)
The Client and Request
I always like it when the Client class is named as a participant in a design pattern, and with CoR, it is a main one directly tied into the Handler. Just the Client, Handler interface, and the Concrete Handler classes make up CoR. When using PHP, you need a calling file, and so an added file calls the Client. The Request object is actually one method smaller than the original Request created for ActionScript. As a getter/setter the setter is in the Constructor function, and so it seemed redundant to add a setter method in addition to the Constructor. The getter method encapsulates the value of the request generated originally in the Client. All three files are included in the following listing:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | <?php //Request class class Request { private $value; public function __construct($weight) { $this->value=$weight; } public function getPounds() { return $this->value; } } ?> <?php //Client class class Client { public function __construct() { $Acme = new GMC(); $Paramount = new Dodge(); $Pinacle = new Ford(); $Acme->setSuccessor($Paramount); $Paramount->setSuccessor($Pinacle); // Generate and process load requests $loadup = new Request(1200); $Acme->handleRequest ($loadup); $loadup = new Request(1650); $Acme->handleRequest ($loadup); $loadup = new Request(1795); $Acme->handleRequest ($loadup); } } ?> <?php //Testing file ini_set("display_errors","2"); ERROR_REPORTING(E_ALL); include_once('Client.php'); include_once('Handler.php'); include_once('Request.php'); include_once('GMC.php'); include_once('Dodge.php'); include_once('Ford.php'); $testClient = new Client(); ?> |
When you test the program, you should see the following output:
A GMC Canyon would be good for this. Weight: 1200
A Dodge Dakota can handle this load. Weight: 1650
This load requires a Ford 150. Weight: 1795
I added the input values (weight) to show that this CoR knew what it was doing. Albeit, it’s not doing much other than demonstrating the CoR structure. However, I’ve got big plans for the CoR in PHP for automatically handling inquiries. The more options available, the more useful the CoR becomes. And of course, since it’s a design pattern, adding and changing options is quite easy.
Some Differences
The biggest differences in the programs are PHP and ActionScirpt 3.0 syntax differences. Here are some you can see immediately:
- PHP uses -> instead of . for linking properties and methods to an object (e.g., myObj->myProp instead of myObj.myProp)
- PHP has no data typing
- PHP requires include for all the class files in use (in the testing file)
- All variables have dollar signs ($) in front of them
- PHP concatenation uses a dot (.) instead of a plus sign(+)
- PHP constructor functions use __construct() instead of the class name
Other kinds of differences are the idiosyncrasies of each language, and you may have to push and pull a bit when applying design patterns of one to the other. However, the nice thing about design patterns is that they are generally applicable to all languages. I had thought that lack of typing to an interface (because of the weak typing of PHP) would be a deal-breaker, but I don’t think so any more. I suppose with a very complex program, you’d miss stronger typing, but from what I’ve seen PHP programs with a good structure work well and are easy to change, are reusable and are loosely coupled. So, in case you’re considering creating PHP design patterns, I’d definitely encourage it, and you’ll find that converting examples from ActionScript 3.0 isn’t all that difficult.
Naturally, we’d like to hear from both ActionScript 3.0 and PHP developers to get your thoughts on this topic. We’d be very interested in applications that use both ActionScript 3.0 and PHP and linking up optimal design patterns so that modules from the two languages can more easily be integrated.

The PHP Chain of Responsibility Design Pattern from ActionScript 3.0 by William B. Sanders, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.

Bill Sanders
Good read, thanks!
In php you can do an __autoload to handle the includes.
I just come across your article. It’s excellent.
Don’t know whether it’s too late or not. I want to share how i do “Program to interface not implementation” in PHP
here’s my code
public static function set_payment(IPayment $payment) {
// use type hinting to make sure that the $payment object
// must implement 'IPayment' interface (This is one what we
// looking for "program to interface not implementation")
$this->payment = $payment
.. some codes
$this->payment->process();
}
In my opinion this “Program to interface not implementation” phase rising up because the downside(pitfall) of “Strict type” language itself.
With any dynamic type languages you always come up with that phase.
e.g.
$i_payment = new ConcretThatImplementIPayment;
// is equivalent this line in flash
var i_payment:IPayment = new ConcreteThatImplementIPayment;
PS. May be there’s only me that think like this :)
Hi Dave,
Thanks for the tip on using _autoload. I’ll give it a try for my next PHP design pattern.
Kindest regards,
Bill
Hi HangTen,
Dude, it’s never too late to add good ideas!
First of all, thanks for the work-around for typing to an interface. Let me see if I’ve got this right. You set up the typing using the format set_someVariable(IdataType $someVariable);. That, I definitely will have to try.
Second, one of the ironies of Strict typing is that it aids in loose coupling. The reason is that typing to the interface commits you only to the interface and doesn’t tie you up with the implementation. You have to think:
If strict typing ever comes to PHP, welcome it. It will loosen you up!
Kindest regards,
Bill
Hi guys!
Great post! I always like to see DP on different languages and how do they come up with some technical solutions.
I remember when I first started programming with AS3 and tried to implement a Singleton. “No private constructor?! What the hell?!” I got really disappointed on that time but there are always some solutions. And in the case of the Singleton, a LOT of solutions.
That’s one of collest things about DP: they are idea-centered solutions. You implement it the best way you can.
Cheers (from the Nederlands now!)
Bill_BsB
Hi Bill,
I like the idea that DPs are idea-centered solutions. If you understand the basic idea; you can create anything in any language. However, while the Singleton is an interesting exercise on how to create a private class, remember, Singletons are evil.
Enjoy the Netherlands–wonderful people there. I attended the University of Leiden years ago. Great experience.
Kindest regards,
Bill