Skip to content

Instantly share code, notes, and snippets.

@Kcko
Created March 23, 2018 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kcko/904d990d0ffbcb68146addfd019bb769 to your computer and use it in GitHub Desktop.
Save Kcko/904d990d0ffbcb68146addfd019bb769 to your computer and use it in GitHub Desktop.
<?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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment