Friday, 1 August 2014

Using Fluent Interface for method chaining

In the fluent interface, one setter method returns the current object ; this is implemented  for doing method cascading (or method chaining) ; please refer to wikipedia for further explanation  http://en.wikipedia.org/wiki/Fluent_interface

In PHP, one can return the current object by using the $this special variable which represent the instance. Hence return $this; will make the method return the instance. The example below define a class Employee and three methods to set its name, surname and salary. Each return the instance of the Employee class allowing to chain methods.

<?php
class Employee
{
    public $name;
    public $surName; 
    public $salary;
 
    public function setName($name)
    {
        $this->name = $name;
 
        return $this;
    }
 
    public function setSurname($surname)
    {
        $this->surName = $surname;
 
        return $this;
    }
 
    public function setSalary($salary)
    {
        $this->salary = $salary;
 
        return $this;
    }
 
    public function __toString()
    {
        $employeeInfo = 'Name: ' . $this->name . PHP_EOL;
        $employeeInfo .= 'Surname: ' . $this->surName . PHP_EOL;
        $employeeInfo .= 'Salary: ' . $this->salary . PHP_EOL;
 
        return $employeeInfo;
    }
}
 
# Create a new instance of the Employee class:
$employee = new Employee();
 
# Employee Tom Smith has a salary of 100:
echo $employee->setName('Tom')
              ->setSurname('Smith')
              ->setSalary('100');
 
# Display:
# Name: Tom
# Surname: Smith
# Salary: 100