PHP fluent interface

23.Nov.2011

PHP fluent interfaces have been around for quite some time. They are often used just for chaining methods of an object so that we get nice readable code.

Good fluent interface takes a while to build, and will take some planning to make object methods work seamlessly. However, if you still haven’t experienced the PHP fluent interface, there is a good way to start, just check out the following snippet.

class Php_Fluent_Interface_Demo {
    protected $_first;
    protected $_second;
    protected $_third;
 
    public function setFirst($firstVal) {
        $this->_first = $firstVal;
        return $this;
    }
 
    public function setSecond($secondVal) {
        $this->_second = $secondVal;
        return $this;
    }
 
    public function setThird($thirdVal) {
        $this->_third = $thirdVal;
        return $this;
    }
}

You have noticed that all setters have one line in common return $this; and this is how you set your methods to be able to chain. Example of usage follows in next snippet:

$phpFluentInterface = new Php_Fluent_Interface_Demo();
$phpFluentInterface->setFirst(1)
    ->setSecond(2)
    ->setThird(3);

I hope that this simple example is enough to get you started if you still haven’t tried PHP fluent interface. Good luck!