Building proxies, decorators and delegates in PHP5
Monday, July 3rd, 2006
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.


