Building proxies, decorators and delegates in PHP5

July 3rd, 2006 by Ivo

In PHP5, you can define methods in an object for intercepting calls to methods of an object and for intercepting access to object member variables. These methods (__get, __set and __call) enable the implementation of very generic proxies, decorators and delegators.

(For those unfamiliar with these design patterns, the extensive descriptions at wikipedia are worth the read.)

What proxies, decorators and delegates have in common is that they all change a part of the behaviour of an underlying object by overriding its methods, while forwarding the rest of the calls to the original object.

I wouldn't like this post to be purely theoretical, so let's use a simple example with decorators to demonstrate the concept.

Suppose we have the following class:

 
class HelloWorld
{
  function sayHello()
  {
    return "Hello World";
  }
 
  function doSomethingElse()
  {
  }
}
 
$obj = new HelloWorld();
echo $obj->sayHello();  // "Hello World"

We would also like to create classes that decorate the hello-saying. I want to have a decorator that makes the output bold, and another one that makes the output italic. (You could create a class that extends HelloWorld, but more in this later. For the moment, assume that inheritance is not an option.)

In classic code, if I wanted to decorate the sayHello method, I could create a decorator object that looks like this:

 
 
class BoldHelloWorld
{
  var $m_object = NULL;
 
  function BoldHelloWorld(&$object)
  {
    $this->m_object = $object;
  }
 
  function sayHello()
  {
    return "<strong>".$this->m_object->sayHello()."</strong>";
  }
 
  function doSomethingElse()
  {
    return $this->m_object->doSomethingElse();
  }
}
 
$obj = new BoldHelloWorld(new HelloWorld());
echo $obj->sayHello(); // "<strong>HelloWorld</strong>"

This would work like a charm, but the problem is in the doSomethingElse method. Well, not really a problem, it's just that I have to redefine it to forward the call to the original object. What if we had 5 methods, or 10? All of them would need to be forwarded.

What if there are member variables in place that should be accessible? You'd have to forward those too. (I know, exposing member variables is Evil, but sometimes the object in question is not developed by yourself and you just have to deal with it.)

PHP5 has excellent ways to solve this, and fairly easy too. It allows us to build a generic base class for our decorators that takes care of the whole forwarding problem. (Credit for this class goes to my coworkers Martin and Peter).

 
 
/**
  * AutoForward baseclass for automatic forwarding of
  * method calls and member variables.
  *
  * @author Peter C. Verhage
  * @author Martin Roest
  */
class AutoForward
{
  var $m_object;
 
  /**
   * Constructor.
   *
   * @param Object $object
   */
  function __construct(&$object)
  {
    $this->m_object = $object;
  }
 
  /**
   * Returns the forwarded object.
   */
  function &__getObject()
  {
    return $this->m_object;
  }
 
  /**
   * Forward method calls.
   *
   * @param String $method method name
   * @param Array $args method arguments
   * @return Unknown method return value
   */
  function __call($method, $args)
  {
   return call_user_func_array(array($this->m_object, $method), $args);
  }
 
  /**
   * Forward property set.
   *
   * @param String $name property name
   * @param Unknown $value property value
   */
  function __set($name, $value)
  {
    $this->m_object->$name = $value;
  }
 
  /**
   * Forward property get.
   *
   * @param String $name, property name
   * @return Unknown
   */
  function __get($name)
  {
    return $this->m_object->$name;
  }
}
 

By overriding __set, __get and __call, any methods to an object of the AutoForward class are automatically forwarded to the contained object.

Let's use this class to create our bold and italic decorators:

 
 
class BoldHelloWorld extends AutoForward
{
  function sayHello()
  {
    return "<strong>".$this->m_object->sayHello()."</strong>";
  }
}
 
class ItalicHelloWorld extends AutoForward
{
  function sayHello()
  {
    return "<em>".$this->m_object->sayHello()."</em>";
  }
}
 
$obj = new ItalicHelloWorld(new HelloWorld());
echo $obj->sayHello(); // "<em>Hello World</em>"

Notice how we no longer defined the doSomethingElse method? It is automatically forwarded to the original object. In fact, an object of type ItalicHelloWorld will behave exactly like a HelloWorld object. Any caller wouldn't know the difference. Except ofcourse that sayHello returns a manipulated result.

I promised to explain why inheritance wouldn't be the solution here. By providing both an ItalicHelloWorld and a BoldHelloWorld, I've tried to demonstrate this. What if you needed a string that was both bold and italic? Which of the two would you extend? PHP doesn't have multiple inheritance, so we would be stuck there.

But not in our example. It would simply be a matter of:

 
 
$obj = new BoldHelloWorld(
new ItalicHelloWorld(
new HelloWorld()));
echo $obj->sayHello(); // "<strong><em>Hello World</em></strong>"

Using this approach, we've worked around the need to have multiple inheritance.

This technique is also useful if you are a fan of Aspect Oriented Programming. You could have an object that implements a certain aspect and applies that to the underlying object. Instead of overriding a single method, you can override __call and implement an aspect.

Let's take security as an example. Suppose we have an object, but we want to secure access to any of its members. We could use the following class:

 
 
class SecurityAspect extends AutoForward
{
  function __call($method, $args)
  {
    if (isAllowed($method))
    {
      return call_user_func_array(array($this->m_object, $method), $args);
    }
    throw new Exception("Caller not allowed to execute $method on this object.");
  }
}
 
$obj = new SecurityAspect(new HelloWorld());
$obj->sayHello(); // throws error if sayHello not allowed

Another aspect that can easily be implemented like this is caching of resource intensive methods. Just add a list of methods to cache, and a member variable to hold results for cached methods.

With this post I've tried to demonstrate the power of PHP5's __call, __get and __set special functions. Java has similar solutions using reflection, but PHP5 makes it much more easy to create constructs like this. This also makes it possible to easily create patterns with small amounts of code.

Feel free to use the code samples in this post. You can link back to this post from your code to explain how the code works, if you like.

11 Responses to “Building proxies, decorators and delegates in PHP5”

  1. July 03, 2006 at 10:25 pm, Dennis Pallett said:

    Why not have the BoldHelloWorld and ItalicHelloWorld classes extend the HelloWorld class? That would make any forwarding unncessary, and it’s how I learnt the decorator pattern.

  2. July 03, 2006 at 10:34 pm, aurelian said:

    So, you can write your own wiki syntax now :)

  3. July 03, 2006 at 10:40 pm, Ivo said:

    That is explained near the end of the post; because you cannot have something that is both bold and italic that way.

  4. July 03, 2006 at 10:48 pm, Stephan Schmidt said:

    The big problem with this approach is, that is will not work if you are using instanceof or type hints in your code.

  5. July 03, 2006 at 10:55 pm, Andrew Bidochko said:

    Why are you using assignment by refernce ($obj = &new HelloWorld())?
    It has been deprecated in php5.

  6. July 03, 2006 at 11:13 pm, Ivo said:

    Thanks, I’ve corrected the samples. Still doing too much PHP4 I guess ;-)

  7. July 04, 2006 at 10:25 am, Dennis Pallett said:

    Yes, you can, both child classes extend the HelloWorld class, and you can still use the decorator pattern, i.e.

    $obj = new ItalicHelloWorld(
    new BoldHelloWorld(
    new HelloWorld()));

  8. July 04, 2006 at 10:39 am, Ivo Jansch said:

    That is indeed correct, this would make the interface the same. However, in your solution, the ItalicHelloWorld would have its own state, meaning that doSomethingElse() would work on member variables of the ItalicHelloWorld instance and not on member variables of HelloWorld instance. (the difference between $this->m_member and $this->m_object->m_member)

    Unless you reimplement all methods, which is the point of this article; using the AutoForward baseclass, you won’t have to do that.

    Also have a look at the security example near the end. It is applicable to virtually any class, which wouldn’t be possible if SecurityAspect would inherit from one of them.

  9. July 04, 2006 at 11:06 am, Dennis Pallett said:

    You’re right about that, although it shouldn’t really matter that ItalicHelloWorld has its own state.

  10. July 04, 2006 at 4:54 pm, Mike Lively said:

    This can be worked around very easily by making the base class and all of it’s decorators extend a parent interface. Using __call does mean that the interface will probably have to be empty. (That is unless you create a seperate interface for each method/group of methods that you anticipate decorating. Which gets cumbersome.)

  11. July 26, 2006 at 4:51 pm, paul said:

    While I think that proxying functions from more then one base object in one environment IS VERY useful when dealing with shared environments I beg you specify this explicitly. IE: This is a shared environment programming pattern do not use it to draw circles…

    Can’t really se any true and undenyable reason to use these techniques while not invoking the all-to-well-known -”not my code, have to go round” reason, which is by the way just a sign of very poor analysis and granulation skills.

    Other then that nice tute. – and I like the oracle halo of the company :D