|
|
<?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;
/** * Cache instance * * @var Cache */ 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(false), $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->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(false), $data)) { return false; } return $this->getInsertId(); }
/** * @param array $data * @param mixed $where * @return int Number of affected rows */ public function update($data, $where) { if (is_int($where)) { $where = $this->identify($this->key) . '=' . (int) $where; } return $this->db->update($this->table(false), $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(false), $where); }
/** * @param bool $autoindent * @return string */ protected function table($autoindent = true) { if (!$this->table) { $this->table = substr(strtolower(get_class($this)), 0, -5/*strlen('Model')*/); } return $autoindent ? $this->identify($this->table) : $this->table; }
/** * @return Cache */ protected function cache() { if (!$this->cache) { $this->cache = Cacher::get(Config::get(__CLASS__, 'MemcacheCache')); } return $this->cache; } }
|