Home > Design Patterns, PHP, Principles > ActionScript 3.0 and PHP 5: Doing Design Patterns

ActionScript 3.0 and PHP 5: Doing Design Patterns

Note: This is one of those posts that begs for reader comments. PHP is a much-loved language of mine, but I just don’t do the kind of applications that require PHP often. As a result, it stays on the shelf until I need it. So, while very familiar with PHP, I do not claim a high level expertise in it. However, judging from the online PHP discussions and PHP publications, lots of developers are well versed in the language. So, for you PHP’ers out there, your comments are welcomed. (Likewise if you’re not familiar with PHP, feel free to comment as well.)

PHP, My Old Friend

PHP has always been a developers programming language. From its inception, you could write PHP using Notepad or TextEdit and not have to worry about some cranky API or IDE. Alternatively, there are plenty of development applications for creating PHP, such as Dreamweaver. Further, you could write email apps as easy as a ‘Hello World’ example. Not only is PHP open source, it is constantly updated and improved by developers working on it because it is important to them. You can plunk it down on top of an Apache server (also open source) and use MySQL (also open source—but maybe not for long) for a database. It runs on Linux, Windows and on Mac OS (it comes standard with Macs as does an Apache server). Further, PHP 5 has real abstract classes! What’s not to like?

Working with Design Patterns in PHP

Not to raise the ire of PHP programmers, but working with design patterns in PHP after getting used to doing so in ActionScript 3.0 (or Java or C#) can be a real challenge. In fact working with OOP principles in a language without typed data can be extremely perplexing. This is not due to the lack of PHP design pattern examples or OOP discussions by top-notch programmers. I found plenty. Rather, when I started working on the PHP portion for the recent Design Patterns at Work Survey, I found many unexpected hitches. Naturally, I didn’t want to create a survey on design patterns and not use a design pattern to create it. It was a simple Strategy pattern, but still, it was important to do it with some modicum of integrity. What follows are some of my discoveries and queries about working with PHP where OOP and design patterns are important.

How Can You Program to an Interface Without Typed Variables?

For Gamma, et al the first principle for minimizing dependencies in programming is,

Program to an interface, not an implementation

In ActionScript 3.0 you have something like the following in programming to an interface:

var instanceNow:MyAbstractClass = new ConcreteClass();

Likewise in Java and C#, you’d see,

MyAbstractClass instanceNow = new ConcreteClass();

All of these languages have strict typing. So how is it possible in PHP— characterized by loose typing—to program to an interface? In looking at numerous examples, all I saw was typing to the implementation. To illustrate, the following example shows building an abstract class with an abstract property and method. To understand this example in PHP, you need to know a couple of things:

  • The => operator is the same as a dot (.) in ActionScript 3.0. So
       $keyInstance->keyMethod()
    in PHP is the same as
       keyInstance.keyMethod()
    in ActionScript 3.0.
  • Variables begin with a $ character. However, when expressed as properties of an object, they do not have the $ character.
  • Variables have no typing or var statements. They are “declared” in a class using access modifiers (e.g., protected $myVar).

If you’re familiar with PHP, the following is pretty simple to follow, and if you’re not, it still should make some sense given the above clues to PHP’s unique features.

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
<?php
abstract class AbClass
{
     public $keyProperty;
 
    // Abstract methods need elaboration in implementation
 
    abstract protected function abFunction();
 
    // All subclasses inherit this method
 
 	public function keyMethod()
       {
        	print $this->abFunction();
		print $this->keyProperty;
    	}
}
 
class ConClass extends AbClass
{
    	protected function abFunction()
	{
        	return "PHP: Detail of abstract method." . "<br />";
    	}
}
 
$keyInstance = new ConClass();
$keyInstance->keyProperty="Key Property: Value of property from abstract class.";
echo $keyInstance->keyMethod();
?>

That little bit of code produces the following:


PHP: Detail of abstract method.
Key Property: Value of property from abstract class.

In ActionScript 3.0, the client would have instantiated the same operations as:

var keyInstance:AbClass =new ConClass();

That’s what it means to program to an interface, and the Gang of Four could not have put it any clearer:

Don’t declare variables to be instances of particular concrete classes. Instead, commit only to an interface defined by an abstract class. You will find this to be a common theme of the design patterns in this book.

So how does one go about creating good PHP that minds its manners as far as OOP principles and design patterns are concerned? In an excerpt from Matt Zandstra’s book, PHP Objects, Patterns, and Practice (Second Edition) I saw the following intriguing kind of code in the context of a Strategy Design Pattern. (Below, I’ve just included a small part and have changed the names to reflect the Strategy pattern structure.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
abstract class Context
{
	private $propertyA;
	private $strategyProp;
 
	function __construct($propertyA, Strategy $strategy)
	{
		$this->propertyA =$propertyA;
		$this->strategyProp = $strategy;
	}
 
	function methodA()
	{
		return $this->strategyProp->methodA($this);
	}
}
?>

In the __construct() function, you can see the parameter pair, Strategy $strategy. Now if you’re a Java or C# programmer, you’ll see that as a typed parameter. (It would be strategy:Strategy in ActionScript 3.0.) However, it turns out to be a way of forming an aggregate relationship between the Context and Strategy classes in a Strategy Design Pattern. (Context delegates to Strategy.) That’s exactly what’s supposed to happen in a Strategy design. However, I’m still not sure what Strategy actually does in the parameter list. Further, if it acts like a typing statement, could it be used to type instances to interfaces? I don’t know, but it’s interesting, and if any of you OOP PHP folks out there know the answer, let us know.

From a Detour to a Mystery

This post started out as a little discussion about building the ActionScript 3.0 Design Pattern at Work survey and trying to be faithful to all of the principles and patterns we’ve discussed in ActionScript 3.0. It led to some mysteries about PHP and OOP, which I find endlessly fascinating. What better challenge could there be than working out design patterns where it appears to be impossible to follow the most fundamental principle of design pattern development—program to an interface, not an implementation.

One possible answer lies in the O’Reilly book, PHP Design Patterns by Stephan Schmidt. When I went to look for it, it was nowhere to be found! It wasn’t on the O’Reilly list or Amazon.com or anywhere. Since I’m one to panic at the drop of a hat, I assumed it has been abducted by aliens, but no. It’s written in German and can be found on the German version of Amazon .com. That’s the end of a promising mystery. Let’s hope it’s translated into English, Spanish, Portuguese and French for us New World types!

Share

No related posts.

  1. May 26, 2009 at 5:24 am | #1

    You may be interested in exploring the Zend PHP framework, which implements the MVC cluster of design patterns..and a few others (Front Controller?). I guess it’s inspired by Ruby On Rails. I haven’t actually used it but it looks cool.

  2. May 26, 2009 at 5:34 am | #2

    Hi David,

    Thanks for the tip. I’ve heard about the Zend PHP framework and took a quick look at it. However, I don’t remember seeing instances typed to an interface. Because abstract classes cannot be instantiated, I have not yet solved the riddle of how to program to an interface instead of an implementation in PHP.

    Zend PHP sounds like a good place to dig. I’ll start shoveling!

    Kindest regards,
    Bill

  3. May 26, 2009 at 8:42 am | #3

    I really like code reference that you use on this site. What is it that you use or where can I find a snippet window like the one you have listed on the page to reference code?

    Great Blog!

  4. Chandima Cumaranatunge
    May 26, 2009 at 9:15 am | #4

    Hi Steve, we use the WP-CODEBOX Plugin for code formatting. Download from:

    http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/

  5. May 26, 2009 at 9:37 am | #5

    Okay great. Thank you for getting back to me so quickly. That is a great plugin.

  6. Chandima Cumaranatunge
    May 26, 2009 at 10:22 am | #6

    Bill, you got me very interested in this as I’ve been developing some WordPress plugins recently. WordPress runs on a PHP-MySQL backend. AFter developing a couple of plugins and themes, I realized that a lot of time was spent trying to locate errors.

    Being a dynamically typed language, PHP errors only appear at run-time. Many errors were type mismatches that would be easily caught in a statically typed language during compile-time. “Trying” is the key here as a PHP type error manifests itself somewhere other than where the culprit resides. One has to backtrace the call stack to isolate the type error.

    I actually ended up writing a logger plugin that enabled me to pretty print PHP objects onto the browser console just to help with debugging. However, logging variables is a poor substitute for strong typing.

    A type check on function parameters would be a big help indeed. I went back to my favorite PHP 5 book – “PHP 5 Power Programming” by Gutmans, Bakken, and Rethans. Lo and behold, PHP 5 does have a built-in type check for function parameters.

    1
    2
    3
    4
    
    function makeSureMyParamsAreGood( MyClass $obj )
    {
        // ...
    }

    When the above function is called, PHP will do an instanceof check to make sure that the $obj is of type MyClass. If not, it will throw an error. The cool thing is that the instanceof check returns true even if $obj is an instance of a subclass of MyClass.

    It would be nice to have a PHP IDE that does type checking. Wonder if Zend Studio does this?

  7. May 26, 2009 at 1:18 pm | #7

    Hi Chandima,

    I’m sort of a Notepad programmer when it comes to PHP. I’m going to play around with the instanceof check. By the way, if you put in:

    < ?php .... and....?> when using the plugin with PHP, you get the color coding:

    Like this:

    1
    2
    3
    4
    5
    6
    
    <?php
    function makeSureMyParamsAreGood( MyClass $obj )
    {
        // ...
    }
    ?>

    Cool, huh?

    Cheers,
    Bill

  8. June 2, 2009 at 11:22 am | #8

    Interesting post. I am a hard core PHP dev. The flash designer in my company pointed me to this article. I enjoyed reading it, and thought I would share a couple of thoughts. First, be careful not to try a do something in a language that it is not intended. PHP is not a strict typed language. If you design pattern is built on the concept of being strict typed, then you probably will need to pick a new pattern.

    Second, if you do need to check the type of item passed you can accomplish it by putting a check on the setting of the property with the PHP magic getter and setter methods. These are methods called by PHP when you try to access an object’s property outside of the object. For example:

    {$key} = $value;
    }
    ?>

  9. June 4, 2009 at 1:46 pm | #9

    Hi Daniel,

    Thank you for your comment–I’m especially interested in how the PHP folks deal with programming to an interface and not an implementation without using typed variables.

    I think you hit the nail on the head in pointing out that you cannot make a non-typed language (such as PHP) do something that it is not intended to do. However, I find lots of PHP design patterns out there, but they all seem to be coding to an implementation and not an interface (abstract class or interface.) Since the first dictum of design patterns by GoF is to program to an interface instead of an implementation, I’m curious how that might be done.

    If you know any PHP coders who use design patterns, I’d like to find out how they do that.

    Thanks,
    Bill

  10. June 4, 2009 at 1:53 pm | #10

    Bill,

    You might want to check out http://www.phpfever.com/. They have lots of PHP design pattern postings. It may not be pure enough to meet your formal def, but I think it gets the benefits of design patterns.

    Daniel

  11. June 5, 2009 at 2:50 am | #11

    Hi Daniel,

    Thanks for the link. I looked at it, and while I did not come any closer to solving the riddle of how to code to an interface instead of an implementation in PHP, it’s a very good PHP site. One of the insights that I liked very much is Will Fitch’s observation that the Factory Pattern (I believe he actually meant Factory Method Pattern) can be used instead of the Singleton. I think that may be useful for those who want Singleton functionality but who do not like the Singleton’s problems (see We Don’t Need No Stinkin’ Singletons).

    I don’t mean to sound like I’ being a purist (and certainly not a prig!) about OOP and Design Patterns. I want to be as inclusive as possible when it comes to OOP/DP. Rather, I’m looking for a way to use design patterns with PHP. I am convinced that there’s a workaround that serves the same function as typing an object to an interface instead of an implementation in PHP, but I just haven’t found it yet. In the original post I noted Matt Zandstra’s code structure:

    ?View Code ACTIONSCRIPT
    1
    2
    3
    4
    5
    
    function __construct($propertyA, Strategy $strategy)
    {
    	$this->propertyA =$propertyA;
    	$this->strategyProp = $strategy;
    }

    Where “Strategy” is an interface in the Strategy pattern. This may be how to program to an interface instead of an implementation in PHP. I’m just not sure though because I’m more of a weekend PHP programmer than a hard core one like many.

    So if you can help us out on this key design pattern principle as it applies to PHP, I’d be most grateful. Maybe Matt’s explanation would make more sense to a PHP programmer than to an ActionScript 3.0 one!

    Kindest regards,
    Bill

  1. May 25, 2009 at 6:56 pm | #1

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>