wikipoints/ground/classes/Model.php

140 lines
3.8 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
class Model
{
private $_primaryKey_;
protected $_tableName_;
private $_id_;
private $_vals_ = array();
function __construct()
{
$this->_primaryKey_ = $this->getPk();
}
function __set($name, $value)
{
$this->_vals_[$name] = $value;
}
function __get($name)
{
return isset($this->_vals_[$name]) ? $this->_vals_[$name] : null;
}
/**
* Получаем Primary Key
* @return type
*/
private function getPk()
{
$res = App::$DB->query("SHOW KEYS FROM " . $this->_tableName_ . " WHERE Key_name = 'PRIMARY'")->fetch(PDO::FETCH_ASSOC);
return $res["Column_name"];
}
/**
* Возвращает объект - запись в БД.
* @param int $id
* @return \Model
*/
function getByPK($id)
{
$this->_vals_ = App::$DB->query('SELECT * FROM ' . $this->_tableName_ . ' WHERE ' . $this->_primaryKey_ . ' = ' . $id)->fetch(PDO::FETCH_ASSOC);
$this->_id_ = $this->_vals_[$this->_primaryKey_];
return $this;
}
/**
* Возвращает массив с ассоциативными массивами, соответствующими записями в БД.
* @param string $where просто строка с условиями: (`id` > 1) AND (`name` == 'TEST')
* @param string $order строка с именем толбца и напрабления: `summ` DESC
* @return type
*/
function getAll($where = '', $order = '')
{
/* TODO: Переделать этот метод. Сделать статическим, возвращать массив объектов. */
$sql = 'SELECT * FROM ' . $this->_tableName_;
$sql .= $where ? ' WHERE '.$where : '';
$sql .= $order ? ' ORDER BY '.$order : '';
$res = App::$DB->query($sql);
$this->_id_ = NULL; // Это больше не конкретная запись
$ready = array();
while ($row = $res->fetch(PDO::FETCH_ASSOC))
{
$ready[$row[$this->_primaryKey_]] = $row;
}
return $ready;
}
/**
* Удаляет запись из БД.
* @param int $id
* @return boolean
*/
function delete($id)
{
return $id ? App::$DB->query('DELETE FROM ' . $this->_tableName_ . ' WHERE ' . $this->_primaryKey_ . ' = ' . $id) : false;
}
/**
* Добавляет новую запись в БД.
* @param array $values - ассоциативный массив соо значениями.
* @return int/boolean - id добавленной записи или false.
*/
function add($values)
{
$request = App::$DB->prepare('INSERT INTO ' . $this->_tableName_ . ' (' . implode(',', array_keys($values)) . ') values (:' . implode(', :', array_keys($values)) . ')');
if ( $request->execute((array) $values) )
{
return $this->getByPK(App::$DB->lastInsertId());
}
else
{
return false;
}
}
/**
* Устанавливает значения полей из массива.
* @param array $values - ассоциативный массив со значениями.
*/
function setValues($values)
{
$this->_vals_ = $values;
}
/**
* Сохраняет объект в БД.
* @return object/boolean
*/
function save()
{
if (!$this->_id_ || !$this->_vals_)
return FALSE;
$values = $this->_vals_;
unset($values[$this->_primaryKey_]);
$request = App::$DB->prepare('UPDATE ' . $this->_tableName_ . ' SET ' . implode('=?, ', array_keys($values)) . '=? WHERE '.$this->_primaryKey_.'='.$this->_id_);
$res = $request->execute(array_values($values));
return $res ? $this : FALSE;
}
/**
* Возвращает значения полей объекта в виде ассоциативного массива.
* @return array
*/
function getValues()
{
return $this->_vals_;
}
}