PHP Method Chaining
I wrote this up to answer a question on FreeNode #Laravel and I thought that someone else might find it helpful. A basic overview of how method-chaining works in PHP.
class QueryMaker
{
$table = '';
$field = '';
// this is a static method, it doesn't
// run on an object, it only runs on a class
public static function make()
{
// create an instance of class
// QueryMaker and return it
return new static();
}
// this is not static, it doesn't run on
// a class, only on an object
public function setTable($name)
{
$this->table = $name;
return $this;
}
// this is also not static
public function setField($name)
{
$this->field = $name;
return $this;
}
// again, not static, just renders
// the "query"
public function flush()
{
return "select {$this->field} from {$this->table}";
}
}
Here is the implementation with method chaining
$query = QueryMaker::make()->setTable('users')->setField('name')->flush();
Here is the implementation without method chaining
$object = new QueryMaker();
$object->setTable('users');
$object->setField('name');
$query = $object->flush();
// the output is: select name from users
The methods setTable() and setField() return $this. In that context $this is the QueryMaker object that was created by make().
Let's go step by step:
$query = QueryMaker::make()->setTable('users')->setField('name')->flush();
The static method QueryMaker::make() returns an object instantiation of the QueryMaker class.
$query = $object->setTable('users')->setField('name')->flush();
$object->table is set, setTable() returns the object instance.
$query = $object->setField('name')->flush();
$object->field is set, setField() returns the object instance.
$query = $object->flush();
The flush method is called on the object, returning the string.