PHP fluent API tips

In his recent post Travis Swicegood is talking about the "Fluent API". This kind of API is very popular in scripting languages and I use it during my work with Zend Framework or jQuery projects. Another good example of such technique is Document Object Model API.

In short, the fluent API allows you code to look like:

PHP Zend Framework example
$select = $db->select()
->from( ...specify table and columns... )
->where( ...specify search criteria... )
->order( ...specify sorting criteria... );

jQuery
$("p.surprise").addClass("ohmy").show("slow");

The concept behind it is to return the object instance in the setter or operation method. This may be the same object or result object or some other object API developer may think the users may want to use.

For example, the DOM appendChild() method returns the added object, the from() method of Zend_Db_Select returns itself, most of jQuery methods return the jQuery object and so on.

In his perfect form chaining allows to skip assigning new class to variable and you may do dozens of operations without even declaring a variable.

But this, unfortunately, is not possible with PHP because its object creation keyword (new) should only be used as:

$var = new MyClass(...);

an it cannot be used for:

new MyClass(...)->method();

or

($q = new MyClass(...))->method();

This is what the discussion on Travis Swicegood's blog is all about. A few solutions was suggested but of course it would be better to fix the PHP engine.

But the developers need some solution right now and the most elegant is to create a nice and dirty wrapper:

function &ref($obj) {
return $obj;
}

ref(new MyClass())->method();

BTW, this function is useful when you calling a function that requires one of arguments to be a reference.

The solution is good, but breaks "type hinting" and PDT will not show you the nice and handy list of method.

The only alternative is to have a function for each class you declare. It can be a method of some factory class, or method of the class itself. Anyway, it is a hack.

Well, happy long live PHP and we hope your developers will improve you and make our live even more better :-)