PHP7 FluentInterface

This commit is contained in:
Dominik Liebler
2016-09-23 10:24:23 +02:00
parent b556436fa2
commit de196765cf
5 changed files with 413 additions and 262 deletions

View File

@@ -2,79 +2,51 @@
namespace DesignPatterns\Structural\FluentInterface;
/**
* class SQL.
*/
class Sql
{
/**
* @var array
*/
protected $fields = array();
private $fields = [];
/**
* @var array
*/
protected $from = array();
private $from = [];
/**
* @var array
*/
protected $where = array();
private $where = [];
/**
* adds select fields.
*
* @param array $fields
*
* @return SQL
*/
public function select(array $fields = array())
public function select(array $fields): Sql
{
$this->fields = $fields;
return $this;
}
/**
* adds a FROM clause.
*
* @param string $table
* @param string $alias
*
* @return SQL
*/
public function from($table, $alias)
public function from(string $table, string $alias): Sql
{
$this->from[] = $table.' AS '.$alias;
return $this;
}
/**
* adds a WHERE condition.
*
* @param string $condition
*
* @return SQL
*/
public function where($condition)
public function where(string $condition): Sql
{
$this->where[] = $condition;
return $this;
}
/**
* Gets the query, just an example of building a query,
* no check on consistency.
*
* @return string
*/
public function getQuery()
public function __toString(): string
{
return 'SELECT '.implode(',', $this->fields)
.' FROM '.implode(',', $this->from)
.' WHERE '.implode(' AND ', $this->where);
return sprintf(
'SELECT %s FROM %s WHERE %s',
join(', ', $this->fields),
join(', ', $this->from),
join(' AND ', $this->where)
);
}
}