Fluent Interface and Method Chaining in PHP

Fluent Interface and Method Chaining in PHP

A Fluent Interface is an object oriented Application Programming Interface - API that provides "more readable" code. A fluent interface allows you to chain method calls, which results in less typed characters when applying multiple operations on the same object.

Fluent interface let us write code like this:

$person->born()->grow()->learn()->work()->die();

Instead of

$person->born();
$person->grow();
$person->learn();
$person->work()
$person->die();

Implementation:

A fluent interface is normally implemented by using method chaining to implement method cascading (in languages that do not natively support cascading), concretely by having each method return this (self). Stated more abstractly, a fluent interface relays the instruction context of a subsequent call in method chaining, where generally the context is defined through the return value of a called method self-referential, where the new context is equivalent to the last context terminated through the return of a void context.

A simple PHP example

class Person
{
  private $name;
  private $sex;
  private $age;
  private $height;
  private $weight;

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

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

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

  public function height($h)
{
    $this->height = $h;
    return $this;
  }

  public function weight($w)
{
    $this->weight = $w;
    return $this;
  }
  public function save()
{
    $properties = get_object_vars($this);
    $str = '';
    foreach($properties as $property){
        $str .= $property.' ';
    }
    return $str;
  }
}

Now we can call the methods on the object of Person like

$person = new Person();
echo $person->name('John')->sex('Male')->age('20')->height('5.8')->weight('78')->save();

// Outputs
# John Male 20 5.8 78

we can call only few of the methods

$result = $person->name('John')->sex('Male')->age('20')->save();

echo $result; 

// John Male 20

we also can call chain methods in different order

$result = $person->name('John')->height('5.8')->weight('78')->sex('Male')->age('20')->save();
echo $result; 
// John Male 5.8 78 Male 20

That's that for now,I will be sharing the same information for JavaScript. Happy coding