<?php
class DB_Select {
protected $db,
$parts = array(
'SELECT' => '*',
'FROM' => '',
'WHERE' => '',
'GROUP BY' => '',
'HAVING' => '',
'ORDER BY' => '',
'LIMIT' => ''
);
public function __construct($db, $table, $alias = null) {
$this->parts['FROM'] = $db->table($table) . ($alias ? " AS $alias" : '');
$this->db = $db;
return $this;
}
public function columns($columns) {
$this->parts['SELECT'] = $columns;
return $this;
}
public function join($table, $alias, $clause, $type = 'INNER') {
$this->parts['FROM'] .= " $type JOIN " . $this->db->table($table) . " AS $alias ON $clause";
return $this;
}
public function where() {
// включаем поддержку плейсхолдеров
$this->db->args = func_get_args();
$clause = (string) $this->prepareStatement();
$this->parts['WHERE'] = $clause;
return $this;
}
public function group($clause) {
$this->parts['GROUP BY'] = $clause;
return $this;
}
public function having() {
$this->db->args = func_get_args();
$clause = (string) $this->prepareStatement();
$this->parts['HAVING'] = $clause;
return $this;
}
public function order($clause) {
$this->parts['ORDER BY'] = $clause;
return $this;
}
public function limit($limit, $offset = 0) {
$limit = (int) $limit;
$limit = $limit > 0 ? $limit : 0;
$offset = (int) $offset;
$offset = $offset > 0 ? $offset : 0;
$this->parts['LIMIT'] = "$offset, $limit";
return $this;
}
public function __toString() {
$sql = '';
foreach ($this->parts as $key => $value) {
if ($value) {
$sql .= "$key $value ";
}
}
$sql .= ';';
return $sql;
}
public function execute() {
return $this->db->query($this);
}
public function fetch() {
return $this->execute()->fetch();
}
public function fetchSingle() {
return $this->execute()->fetchSingle();
}
public function fetchAll() {
return $this->execute()->fetchAll();
}
public function fetchCol() {
return $this->execute()->fetchCol();
}
public function fetchPairs() {
return $this->execute()->fetchPairs();
}
public function getPage($limit, $page = 1) {
$page = (int) $page;
$offset = $limit * $page - $limit;
$this->limit($limit, $offset);
return $this->fetchAll();
}
}
?>
Я вот думаю нужен ли он в принципе. Пример с ним такой:
$limit = 5;
$page = isset($_GET['page']) ? $_GET['page'] : null;
// При вызове метода select создается объект DB_Select
$arr = $db->select('news')->order('id DESC')->getPage($limit, $page);
Этот код аналогичен такому:
$limit = 5;
$page = isset($_GET['page']) ? $_GET['page'] : null;
$page = (int) $page;
$page = $page > 1 ? $page : 1;
$offset = $page * $limit - $limit;
$arr = $db->rows("SELECT * FROM :news ORDER BY id DESC LIMIT $offset, $limit");
вообще есть поддержка плейсхолдеров
// можно и так
$arr = $db->rows("SELECT * FROM :news ORDER BY id DESC LIMIT ?u, ?u", $offset, $limit); // ?u - unsigned int
// или даже так
$arr = $db->rows("SELECT * FROM :news ORDER BY id DESC LIMIT 2?u, 1?u", $limit, $offset);
Вот думаю он(класс) по сути бесполезен какими его методами можно дополнить?