You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

135 lines
2.8 KiB

<?php
/**
* Класс модели данных
*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage Model
* @since 2010-02-16
* @version SVN: $Id$
* @filesource $URL$
*/
abstract class Model
{
/**
* DbDriver instance
*
* @var DbDriver
*/
protected $db;
protected $cache;
protected $table;
protected $connection = 'default';
protected $key = 'id';
public function __construct()
{
$this->db = Db::connect($this->connection);
}
/**
* @return int
*/
public function getInsertId()
{
return $this->db->getInsertId($this->table(), $this->key);
}
/**
* @param string $ident
* @return string Quoted identifier.
*/
public function identify($ident)
{
return $this->db->quoteIdentifier($ident);
}
/**
* @param mixed $value
* @return string Quoted value.
*/
public function quote($value)
{
return $this->db->quote($value);
}
/**
* @param int $id
* @return object
*/
public function get($id)
{
$sql = 'SELECT * FROM ' . $this->identify($this->table())
. ' WHERE ' . $this->identify($this->key) . '=' . (int) $id;
return $this->db->query($sql)->fetch();
}
/**
* @param array $data
* @return int Affect row or id of inserted field.
*/
public function save($data)
{
$key = isset($data[$this->key]) ? $data[$this->key] : false;
$result = false;
if ($key) {
unset($data[$this->key]);
$result = $this->update($data, $this->identify($this->key) . '=' . (int) $id);
} else {
$result = $this->insert($data);
}
return $result;
}
/**
* @param array $data
* @return int Id of inserted row
*/
public function insert($data)
{
if (! $this->db->insert($this->table(), $data)) {
return false;
}
return $this->getInsertId();
}
/**
* @param array $data
* @param mixed $where
* @return int Number of affected rows
*/
public function update($data, $where)
{
return $this->db->update($this->table(), $data, $where);
}
/**
* @param mixed $where
* @return int Number of affected rows
*/
public function delete($where)
{
if (is_int($where)) {
$where = $this->identify($this->key) . '=' . (int) $where;
}
return $this->db->delete($this->table(), $where);
}
/**
* @return string
*/
public function table()
{
if (! $this->table) {
$this->table = rtrim(strtolower(get_class($this)), 'model');
}
return $this->table;
}
}