Posts Tagged ‘magic methods’

Validating OCL constraints in PHP objects

Thursday, November 15th, 2007

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'.

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.