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.