Fluent Interfaces in PHP

A fluent interface is a way of Object Oriented Programming created to simplify your code and make it more readable.
PHP 5 added Support for dereferencing objects which are returned from methods, that allows the chaining of methods of an object together. This is accomplished by having the method return a reference to the object itself (return $this;).
You may call as many methods as you want just by adding them to the chain

Here is an example of a class without a fluent interface:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php 
class User
{
    private $name;
    private $lastName;
    private $username;
 
    function setName($name)
    {
        $this->name = $name;
    }
 
    function setLastName($lastName)
    {
        $this->lastName = $lastName;
    }
 
    function setUsername($username)
    {
        $this->username = $username;
    }
 
}
 
$user1 = new User();
$user1->setName('John');
$user1->setLastName('Smith');
$user1->setUsername('jsmith');

And here is the same example now with a fluent interface:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php 
class User
{
    private $name;
    private $lastName;
    private $username;
 
    function setName($name)
    {
        $this->name = $name;
        return $this;
    }
 
    function setLastName($lastName)
    {
        $this->lastName = $lastName;
        return $this;
    }
 
    function setUsername($username)
    {
        $this->username = $username;
        return $this;
    }
 
}
 
$user2 = new User();
$user2->setName('Juan')
      ->setLastName('Perez')
      ->setUsername('jperez');

In which cases should you use fluent interfaces?
Their use is almost intuitive, but the rule of thumb says to use them when you have all the data you need to complete the chain of methods and most important, when none of the methods return any information to it’s caller

You may find fluent interfaces in fluent APIs (such as Zend_Db)

Here’s an example of Zend_Db_Select using fluent interfaces:

1
2
3
4
$select = $db->select()
             ->from( 'user' )
	     ->where( 'role = ?', 'admin' )
	     ->order( 'user_id' );

In conclusion, fluent interfaces are very easy to implement, have a very small cost and they are very useful in order to make your code more readable

One Response to Fluent Interfaces in PHP

  1. Pingback: PHP 5.4 is almost here! Array Dereferencing | Open Source Consulting

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">