PHP 4 - 7, Offers Chaining Function With Slight Differences, but this Post and Example Focuses on PHP 7's.
Study the Example Below, Take note of the Power Array, Contatenation and Conditional Statements Have
<?php
class DBManager
{
private $selectables = array();
private $table;
private $whereClause;
private $orderClause;
private $limit;
public function select() {
$this->selectables = func_get_args();
return $this;
}
public function from($table) {
$this->table = $table;
return $this;
}
public function where($where) {
$this->whereClause = $where;
return $this;
}
public function order($type) {
$this->orderClause = strtoupper($type);
return $this;
}
public function limit($limit) {
$this->limit = $limit;
return $this;
}
public function result() {
$query[] = "SELECT";
// if the selectables array is empty, select all
if (empty($this->selectables)) {
$query[] = "*";
}
// else select according to selectables
else {
$query[] = join(', ', $this->selectables);
}
$query[] = "FROM";
$query[] = $this->table;
if (!empty($this->whereClause)) {
$query[] = "WHERE";
$query[] = $this->whereClause;
}
if (!empty($this->orderClause)) {
$query[] = "ORDER BY ID";
$query[] = $this->orderClause;
}
if (!empty($this->limit)) {
$query[] = "LIMIT";
$query[] = $this->limit;
}
return join(' ', $query);
}
}
$db = new DBManager();
$db->
select()->from('userTable')->where(user = 1)->limit(10)->result();// SELECT * FROM userTable WHERE user = 1 LIMIT 10;
Comments
Post a Comment