Trying to grow the PHP market
November 28th, 2007 by Ivo
Sometimes recruiting efforts yield very nice results.
As of this week, Mikko Koppanen works in our Ibuildings UK team. Mikko is known from his Imagick extension, a wrapper to use ImageMagick in PHP.
The nice thing about this is that now we finally have someone on board who knows how to write PHP extensions.
A few weeks ago, Stefan Koopmanschap joined our Dutch team. Stefan is, among other things, in the board of the Dutch PHP User Group, and maintains the Dutch Symfony site.
With these 2 additions to our team, our PHP army is growing steadily, allowing us to continuously improve our support to companies in the UK and The Netherlands that are taking PHP seriously. PHP is rapidly moving into the realm of big corporations, and this means that there's a lot of demand for PHP professionals.
In the past weeks, we've been in contact with several major Dutch websites that are planning to move from java or .net to PHP, which is a very good sign.
Also, we've started working with several Computer Science institutes to add PHP to their curriculum. Most of them are already doing things with PHP, but often this is limited to very basic applications, a CMS, a blog etc. We're now helping them to breed better PHP programmers by teaching proper OO, Design Patterns, MVC, frameworks etc.
Traditionally, these institutes have been Java and .NET oriented, and we hope this will help show more people how PHP is a viable language for serious web applications.
[marketing mode] If you want to join us in our efforts to bring PHP to the business world, we still have openings [/marketing mode]
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'.
DPC2007 and Zend UK Business Conference recap
July 4th, 2007 by Ivo
On june 16th we organized the first Dutch PHP Conference in Amsterdam. The event was attended by more than 250 people and with speakers such as Cal Evans, Kevlin Henney, Lukas Smith, Derick Rethans and many others, I think it was a great event.
We've decided to make it a yearly event, so mark June 14, 2008 in your agenda for the next instalment.
I did a presentation on business frameworks (and ATK in particular) at the conference, the slides of which can be found on slideshare.
The DPC was not the only new conference, last monday I visited the first Zend UK PHP for Business Seminar organized by the London office of Zend. This conference was targeted at 'business people', and featured speakers such as Zeev Suraski, Harold Goldberg (Zend's new CEO), David Boloker (IBM) and Clint Oram (SugarCRM).
I had the honor of presenting a talk on 'enterprise PHP development' on the seminar. Since it was targeted at business people, I explained the development process of PHP applications using metaphors. What may be obvious for most of us, isn't so obvious for a lot of people and companies, so I found it important to talk about the process surrounding PHP development, and not just plain PHP coding itself.
Below are the slides of this talk:
This is the 7th presentation I did in 3 months time; I'm beginning to get the hang of this.
PHP on IBM’s System-i
June 8th, 2007 by Ivo
Some of the developers at Ibuildings are working with PHP on IBM's System-i platform. If that name doesn't ring a bell, it has been called 'iSeries' for a while and it's basically a new name for the old AS/400. If you're old enough to remember Happy Days you probably remember those nifty 'green screens' that they used to use in stores, banks etc. There's a 90% chance that these green screen applications were running on AS/400.
The green screens have mostly made way for more modern interfaces, but the servers that run them still exist today. Many of the applications on them have been modernized by adding a web-interface to the existing applications.
There are several ways to make a web interface for green screen applications, or 'RPG programs', as System-i developers call them; RPG is the programming language that they traditionally use on those machines, and it is complete abacadabra to most PHP developers.
For a while now it is possible to use Java to make webinterfaces on System-i, and there are several cgi based tools. And recently IBM and Zend have teamed up to port PHP to the i5/OS operating system. So far this port seems succesful; one of the reasons is perhaps that PHP is easier to adopt by traditional System-i developers than Java, which forces you to learn Object Oriented Programming. In PHP you can do OOP, but you don't have to. You don't even have to use functions, and this is a lot closer to classic System-i languages (although I would of course recommend any System-i developer moving to PHP to learn at least about procedural programming).
When running PHP apps on System-i, you can use the standard db2 database extension to access the db2 database, but alternatively you can also use the 'i5 toolkit' that is available in PHP on i5/OS. There are some subtle differences, and if you find yourself having to write PHP applications for System-i, it's good to know about how to use the i5 toolkit to use the db2 database. Harrie Verveer has written an article on this topic on our company blog. It explains one of the differences between the db2_* and i5_* functions, but it contains some sample code and as such is a nice example of how to use the i5 functions.
System.out.print in PHP
March 9th, 2007 by Ivo
We are recruiting people on a regular basis, and since it's sometimes difficult to find people with both a computer science background and PHP experience, we also recruit people that are fluent in other languages. Teaching a c++/java/delphi-guy to do PHP in general is easier than teaching a PHP hobbyist good engineering practices.
So yesterday I was reviewing a code sample that a job applicant had written during a test and I encountered the following line of code:
System.out.print($result);
It's not hard to guess what his background was
, but I was initially stunned that this actually works in php.
My first thought was that this was because I installed the Java Bridge from Zend Platform, but the bridging API does not allow the direct use of java objects like this. So was there some evil hidden hack in PHP?
Of course not; eventually the truth was uncovered by the notices in the errorlog:
PHP Notice: Use of undefined constant System - assumed 'System'
Ah, that makes sense. It just sees them as constants which do not exist and are interpreted as strings, and apparently, this is a valid PHP statement as well:
"this"."is"."a"."string";
I cannot find any practical use for being able to write a statement without assignment or output like that, but it does enable code beautification:
I.need.to.get.some.sleep(1);
Of course I would have to strongly advise against this but it was fun to notice that this works.
P.S. shameless plug: this week we launched the first preview of our new web 2.0 pet project: http://www.mockatoo.com; not much to see just yet, but consider it a preview of what we are up to.
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.