John Main Logo

John Main

Code. Design. Hosting. Maintenance.

11
Jul '14

Fluent, also known as chaining, is a very simple design technique to help clean up the way you call your functions within objects. It’s a very simple concept, and supported by many of the big frameworks, but is surprisingly under-used out in the wild.
Basically, the idea is that with every function call that isn’t designed to return a specific response (i.e. setters rather than getters) returns the parent object.
As an example, imagine you had a ‘Person’ object where you could had setters for the name, age and height. In the non-fluent world you might have some code that looks like this:

$person = new Person();
$person->setName(‘John’);
$person->setAge(33);
$person->setHeight(‘6 feet’);

But in the fluent world you could do the following:

$person = new Person();
$person->setName(‘John’)->setAge(33)->setHeight(‘6 feet’);

And all that is needed to be able to use fluent calls is to change functions such as this:

public function setName($name) {
$this->name = $name;
}

To this:

public function setName($name) {
$this->name = $name;
return $this;
}

Much nicer I’m sure you’ll agree!
Of course proper code ninjas would generally use the __call method to handle setting and getting without the need to define individual functions for individual fields but the principle will still work there, just return $this when you’ve done your logic and you’ll be living in the fluent world.