Fluent Interface design pattern is used to define class methods/properties in a way that they are easy to read/follow just like a plain sentence in natural language.


Example


Class


class Traveller
{
private $who;
private $from;
private $time;
private $day;
private $month;
private $year;
private $by;
private $to;

public function setWho(string $who): self
{
$this->who = $who;

return $this;
}

public function setFrom(string $from): self
{
$this->from = $from;

return $this;
}

public function setTime(string $time): self
{
$this->time = $time;

return $this;
}

public function setDay(string $day): self
{
$this->day = $day;

return $this;
}

public function setMonth(string $month): self
{
$this->month = $month;

return $this;
}

public function setYear(int $year): self
{
$this->year = $year;

return $this;
}

public function setBy(string $by): self
{
$this->by = $by;

return $this;
}

public function setTo(string $to): self
{
$this->to = $to;

return $this;
}

// We are actually not interested in this method but adding for printing purposes
public function __toString(): string
{
return sprintf(
'%s will travel from %s to %s at %s on %s in %s %d by %s.',
$this->who,
$this->from,
$this->to,
$this->time,
$this->day,
$this->month,
$this->year,
$this->by
);
}
}

Usage


$traveller = new Traveller();
$traveller
->setWho('Inanzzz')
->setFrom('London')
->setTo('Liverpool')
->setTime('11:00')
->setDay('Monday')
->setMonth('January')
->setYear(2019)
->setBy('train');

echo $traveller->__toString();
echo PHP_EOL;

Result


$ php index.php 
Inanzzz will travel from London to Liverpool at 11:00 on Monday in January 2019 by train.