Posts Tagged ‘design patterns’

PHP Advent Calendar

December 10th, 2007 by Ivo

I had the honor of writing the entry for day 9 of the PHP Advent Calendar. My entry is about Design Patterns.

The PHP Advent Calendar is an initiative of Chris Shiflett. Every day until Christmas, people from the PHP community will post entries on PHP related subjects. Topics covered so far include Testing, Security, Documentation, SPL and there are many more.

Sean Coates created a nice interface to the calendar that makes it easy to navigate through all the entries that have been posted. You can find it here.

Validating OCL constraints in PHP objects

November 15th, 2007 by Ivo

Last week, I attended a Code Camp for the 'Xenerix' project, a research project at a local Computer Science faculty. In that project, we're using all kinds of technologies, including PHP, Ruby and Java.

In this particular session a major subject was OCL. For those who are not familiar with the term: Object Constraint Language, a formal method to specify constraints that objects in an object model should respect. To give a practical example: if you have a class 'Creditcard', you could define the constraints 'self.limit > 0' when withdrawing an amount.

While the goal of the code camp was to do some nifty things with OCL and Ruby, I wanted to see if I could create a method to easily implement OCL constraints in arbitrary PHP objects. (Mainly triggered by one of the students, who discovered that a search for 'OCL and PHP' only resulted in pages that were written in PHP, and about OCL. There weren't any pages about how OCL can be used in PHP.)

As a starting point I created a small testcase with 2 classes, based on a testcase that one of the students used to explain what OCL was. The testcase contains a class 'Creditcard' and a class 'Person'. A creditcard has a limit, an expiration date and an owner (of type Person). A person only has a name. The following constraints apply:

  • When setting the cardholders name of the card, this name should match the name of the owner.

  • You can only withdraw money when the card is not expired.
  • Whatever happens, the limit of the card may not be less than zero.

These constraints can be expressed in OCL like this:

  • self.name = owner.name

  • self.expirationdate > now
  • self.limit > 0

I needed a method to specify the OCL constraint in the class. Although I'm against using docblocks as annotations, annotations in itself is a nice principle, so I decided that for this experiment, I would use docblock based annotations to specify the constraints (until PHP supports true annotations).

Here are the simple classes, annotated with their constraints:

 
 
class Person
  {
    public $name;
 
    public function __construct($name)
    {
      $this->name = $name;
    }
  }
 

This is just a basic little class with a constructor that lets us pass a name. None of the constraints apply to the Person class so we don't specify any OCL here.

 
 
  /**
   * @constraint self.limit > 0
   */
  class CreditCard
  {
    public $limit;
    public $owner;
    public $expirationdate;
 
    /**
     * @constraint self.name = owner.name
     */
    public $name;
 
    public function __construct($limit)
    {
      $this->limit = $limit;
    }
 
    function setOwner($owner)
    {
      $this->owner = $owner;
    }
 
    function setName($name)
    {
      $this->name = $name;
      $this->validate($name);
    }
 
    /**
     * @constraint self.expirationdate > now
     */
    function withdraw($amount)
    {
      $this->limit -= $amount;
    }
  }
 

This is the Creditcard class, which has all the constraints added as annotations. Note that the location of the constraint matters: there's a class-level constraint (that always applies), there's a method-level constraint (that applies whenever someone wants to call the method) and a propertylevel constraint (when someone sets a property to a certain value).

The following code runs a small testcase that performs some method calls and property operations:

 
 
  $cc = new CreditCard(2000);
  $cc->owner = new Person("Hans");
  $cc->name = "Hans";
  $cc->expirationdate = "2006-08-12";
  $cc->withdraw(100);
  $cc->withdraw(3000);
 

Now I needed to find a way to validate the OCL constraints at runtime.

Getting the constraints from the docblocks would be the easy part, the Reflection API can help with that. The hard part would be actually applying them to the object.

My first thought was that every object could be derived from some OCLBaseObject that supports OCL validation. However, this would be very inflexible, as often, a class will already have a baseclass, and this would severely limit us in our class hierarchy.

Then, I thought about using magic methods (__call and __set) to intercept all calls and property set operations. However, this is not possible, as __call and __set only intercept calls and properties that do not exist.

The least clean solution would be to add something along the lines of $this->validate() to each and every method and setter of the class, for example:

 
  function withdraw($amount)
  {
      $this->validate(....)
      ....
  }
 

However, this would bloat all classes, it would be errorprone and it would not be clean.

Finally, I came up with a solution that roughly combines the three approaches above:

 
  try
  {
    $cc = new OCLWrapper(new CreditCard(2000));
    $cc->owner = new OCLWrapper(new Person("Hans"));
    $cc->name = "Hans";
    $cc->expirationdate = "2006-08-12";
    $cc->withdraw(100);
    $cc->withdraw(3000);
 
  }
  catch (Exception $e)
  {
    echo $e->getMessage()."n";
  }
 
  echo "Owner's name is: ".$cc->owner->name."n";
  echo "Cardholder's name is: ".$cc->name."n";
  echo "Card balance: ".$cc->limit."n";
 

When I run this example (I'll get to the new OCLWrapper class in a minute), every call that violates a constraint results in an Exception. The classes retain their original implementation, even returntypes are unaffected.

So how did I implement this solution? Instead of inheritance, I use composition, in the form of a Decorator design pattern. This way, classes can still have their own inheritance hierarchy, and each class instance can be decorated with an object that adds the OCL validation functionality.

To be able to raise an error without changing the methods or their returntypes, I used exception handling.

The third part of the solution is to call an OCL validation on each and every method call and property setter. Instead of doing this in the actual methods, I could easily do this in the decorator class, because it has no own methods and setters, and thus will funnel all calls through its __call/__set magic methods to the underlying actual object.

As you can see in the above example, all it takes now is to wrap an object in an OCLWrapper object, and the OCL constraints will be validated on each method call or property setter.

Finally, I had to write the OCLWrapper class itself. It would have to transparantly support method and property access forwarding to the original object, it would have to be able to fetch constraints from the docblocks and to validate constraints on an obect.

This was easier than I thought, using PHP's Reflection API and a set of magic methods. (The hardest part: actually parsing the OCL syntax; I've used an evil harcoded string replacer to parse simple statements for now: if someone likes to implement a true parser, be my guest :-) )

The class is a bit big to post here, so I've attached it as a download. Rename it to class.oclwrapper.php once you downloaded it (thank you wordpress for mangling the filename :-) ).

If you want to run the sample: place the class.oclwrapper.php file in a directory, put the example code in a separate file, include the class.oclwrapper.php, and run the sample code. You'll see exceptions when you change the testcase to do stuff that's not allowed (such as withrdawing more than the limit).

This was, for me at least, a nice experiment that demonstrates how PHP5's OO features can be used to implement a solution for 'annotation based OCL validation'.

Mixins in PHP

August 23rd, 2006 by Ivo

One of the concepts I like in Ruby is the concept of 'mixins'. Mixins are a way of 'mixing in' functionality of other classes.

A kind of 'multiple inheritance' like approach, only without actual inheritance. It is similar to interfaces, but interfaces only tell you that an object must implement certain methods, whereas mixins also provide an implementation.

It's a bit hard to describe in a few sentences, but this article and the pragmatic programmer's guide provide a good explanation. But I'll explain the concept with examples below.

In the past, there have been attempts to apply mixins to PHP, but this, back in 2002, required quite some cumbersome code, due to the limitations that PHP4 had at that time. I was wondering if some of PHP5's new features would make this easier, and I managed to create a mixin solution with only a few lines of code.

I'll start with the example that explains the mixins, and after that, I'll show the code that makes it possible. I'll end this post with a few quirks that I encountered, for which I solicit comments to improve the solution.

Classes to mixin

Let's first create some classes that can be mixed in. I've created two, that each implement some display functionality:

 
  class Alertable
  {
    function alert()
    {
      $str = $this->toString();
      echo '<script language="javascript"> alert(''.$str.''); </script>';
    }
  }
 
  class Blinkable
  {
    function blink()
    {
      echo "<blink>".$this->toString()."</blink>";
    }
  }
 

The classes are plain and simple, they have a single method that contains the display logic. One displays a javascript alert, the other displays a blinking text. The first thing to notice here is the call to $this->toString(). There is no method called toString to be found in the class. This is no problem however, because these classes will never be used directly. They will be mixed in, in another class, and $this will point to the instance of that class after being mixed in. We only require the class that mixes in these methods, to have a toString method.

Applying the mixins

Using the mixins is fairly easy:

 
 
  class Hello extends Object
  {
    var $mixins = array("Alertable", "Blinkable");
 
    function toString()
    {
      return "Hello World";
    }
  }
 
  $o = new Hello();
  $o->alert();
  $o->blink();
 

The class Hello extends 'Object', which is a class I wrote. It makes the mixins possible. I'll get to this class later. But let's first look at the effect of applying the mixin.

In the member variable $mixins, I store an array of classes I want to mix in. Then, I create an instance of the class, and I can call alert() and blink() on this object, as if the methods were part of the Hello class. Notice how this looks quite natural? The user of the class won't notice that these methods are actually defined elsewhere, and the developer of the class has an easy way of reusing functionality.

As with inheritance, the methods are overridable: if I would still define a custom alert() method on the Hello class level, this method would be called instead of the mixin. This makes it possible to override parts of the behaviour of the mixins.

How it works

Let's take a look at how this works. The handling of the mixins is done by the Object class. There are two key elements in this solution. First, I make use of the PHP5 magic method '__call' to intercept calls to the objects, and redirect methods to the mixins when necessary. Second, there is a little known, but for mixins very important, feature in PHP, which is explained in the oop basics of the PHP manual:

"$this is a reference to the calling object (usually the object to which the method belongs, but can be another object, if the method is called statically from the context of a secondary object)."

It is a mystery to me why such a confusing concept is the first thing in the 'basics' page, but it is very useful. What this basically means that $this does not necessarily point to the current object, but to the calling object, as long as the method is called statically. You've noticed the $this reference in the Blinkable class above; What I basically did was make sure that the method in the mixin was called statically and voila, $this points to the object that is using the mixin, and the mixed in class code looks very natural, like it is a part of the class it will be mixed into.

Here is the code for my Object class:

 
  /**
    * Generic base class for all objects that want to make use of
    * mixin functionality.
    */
  class Object
  {
    private $_mixinlookup = array();
 
    // The constructor takes a look at the mixins, and creates a lookup
    // array, so upon a method call, we can quickly determine whether the
    // method was mixed in.
    function Object()
    {
      if (is_array($this->mixins))
      {
        foreach($this->mixins as $mixin)
        {
          $methods = get_class_methods($mixin);
          if (is_array($methods))
          {
            foreach($methods as $method) $this->_mixinlookup[$method] = $mixin;
          }
        }
      }
    }
 
    // The __call magic method intercepts any method that does not exist
    // and falls back to one of the mixins if they define the method that is
    // being called.
    function __call($method, $args)
    {
      if (isset($this->_mixinlookup[$method]))
      {
        $elems = array();
        for ($i=0, $_i=count($args); $i<$_i; $i++) $elems[] = "$args[$i]";
        eval("$result = ".$this->_mixinlookup[$method]."::"
            .$method."(".implode(',',$elems).");");
        return $result;
      }
      trigger_error('Call to undefined function '.$method, E_USER_WARNING);
    }
  }
 

This code won't win any performance prizes unfortunately, I had to use eval to dynamically call a static method. Other, more efficient ways should work, but I'll explain why they didn't in the 'Quirks' section below. For many types of application however, the performance penalty is low compared to the power of mixins that you get.

Practical application

Now that I've explained the concept of mixins, and how to make it work in PHP5, I'll give some examples of when to use it. In the real world, you probably won't be using Blinkables, but there is a lot of functionality you can think of that can be mixed in to make classes powerful. For example, if you have a custom Collection class, and you create methods to access all its elements, you could easily create mixins such as Sortable, Enumerable and Iterator. These would add sort, enumeration and iteration methods to your object, without cluttering your object with the code.

Also, whenever you find yourself in a situation where you think you need multiple inheritance, rethink the issue and see if mixins are suitable. Often, you'll find that mixins accomplish exactly what you hoped to accomplish if you had multiple inheritance.

Quirks

I promised to end with some quirks I ran into. You can safely skip this section if you're not interested in gory details. :-)

There was actually only one problem that I encountered that lead me to use eval() for the mixin functionality. I've talked about the $this pseudo-variable and how when called statically, $this points to the calling object. Well, even though this is documented in the first part of the oop basics in the PHP manual, it only works in the case where a method is called with the classname::methodname construction. What I would've liked to use, was call_user_func_array or even better, Andrei's Reflection API, which is much more powerful. With the reflection API, the __call method would've looked like this:

 
 
  function __call($method, $args)
  {
    if (method_exists($this, $method))
    {
      return call_user_func_array(array($this, $method), $args);
    }
    if (isset($this->_mixinlookup[$method]))
    {
      $method = new ReflectionMethod($this->_mixinlookup[$method], $method);
      return $method->invoke(NULL, $args);
    }
    trigger_error('Call to undefined function '.$method, E_USER_WARNING);
  }  
 

This would've been more clean, and probably is faster. Now why doesn't this work? First, to call the method statically, I have to pass NULL as first parameter to invoke. This leads to the following error however:

Non-object passed to Invoke()

The reason is that invoke refuses to call my static method if it has not been defined with the 'static' keyword. Easy, you would think, just make your method truly static:

 
  static function blink()
  {
    echo "<blink>".$this->toString()."</blink>";
  }
 

This leads to a different error:

Fatal error: Using $this when not in object context

This kind of invalidates the whole '$this refers to the calling object' part of the documentation. I'm not sure if I should file a bug report for this, comments are appreciated. (I guess that even if it would not throw an error, it probably wouldn't work anyway because $this would be pointing to the ReflectionMethod object instead of my object instance).

Conclusion

I've tried to demonstrate how the powerful concept of Mixins can be applied in PHP. Since it only takes a few lines of code, I guess it would not be hard to make this a standard feature of the PHP language, so I would really like to see true mixin support in PHP6. But if that doesn't happen, I hope to have provided a fairly easy way to apply the concept to your PHP classes anyway.

Feel free to use the code samples in this post, a reference to the post in your code would be appreciated but is not required.

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.