The technical definition of “Fluent Interface”, as defined by Wikipedia, is: “An object oriented construct that defines a behavior capable of relaying the instruction context of a subsequent call.“. It’s just as sexy as it sounds.
In short: any Object Oriented language allows you to call upon a new method, directly followed by another one and still updating the same parent object.
Code explains this easier. The following examples creates a one-armed, one-legged and one-headed person.
class Person { public function addLeg() { // Adds a leg } public function addArm() { // Adds an arm } public function addHead() { // Adds a head } // .... and the list goes on } $person = new Person(); $person->addLeg(); $person->addArm(); $person->addHead();
After creating an instance of the object Person, we call upon every method once to add a certain body part.
If we slightly rewrite the class, by returning the object itself upon every method call, we can also write those method calls like this.
class Person { public function addLeg() { // Adds a leg return $this; } public function addArm() { // Adds an arm return $this; } public function addHead() { // Adds a head return $this; } // .... and the list goes on } $person = new Person(); $person->addLeg()->addArm()->addHead();
While this may, or may not, help in readability – the option to use Fluent Interfaces exist in PHP5 (and JavaScript as well, in the same way). It’ll depend on the situation whether or not this is useful. I can see this creating very chaotic code, and it’s a serious PITA to handle errors or exceptions this way.
Enabling chaining makes the final code less cluttered – jQuery is perhaps the best example for this. I used this method in many of my own scripts(for eg. my PHP Image Class)
Depending on the project you’re working on, this can be a gift or a curse. It’s not always possible to use fluent interfaces because the return types might be needed (without using a ByReference parameter). While it’s perfect in your Image Class, I have my doubts on most other projects.
When trying to cram too much onto too little space, you loose a great part of your readability. Sometimes, spreading your code over multiple lines is a good thing.
One place I’ve had a lot of success working with this is when using public static methods to return an instance for a class. Something like …
foo::bar($x)->baz();
… can combine a lot of functionality into a tight space and, if your “bar” and “baz” methods are more appropriately named, it can remain pretty clear.