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.

252 lines
6.0 KiB

  1. <?php
  2. /**
  3. * Класс модели данных
  4. *
  5. * @copyright NetMonsters <team@netmonsters.ru>
  6. * @link
  7. * @package Majestic
  8. * @subpackage DB
  9. * @since
  10. * @version SVN: $Id$
  11. * @filesource $URL$
  12. */
  13. abstract class Model
  14. {
  15. private $handler;
  16. protected $table = false;
  17. protected $primary_key = 'id';
  18. function __construct()
  19. {
  20. $this->handler = DBConnector::getConnect(Env::getParam('db_settings'));
  21. }
  22. /**
  23. * Выполняет запрос и возвращает сырой результат
  24. *
  25. * @param string $sql
  26. * @return resource
  27. */
  28. function exec($sql)
  29. {
  30. if (DEBUG_ENABLE) {
  31. $time = microtime(true);
  32. }
  33. $res = DBConnector::query($this->handler, $sql);
  34. if ($error = DBConnector::error($this->handler)) {
  35. throw new MJException("<b>Query Error:</b>\n".$sql."\n<b>Error:</b>\n".$error, 1);
  36. }
  37. if (DEBUG_ENABLE) {
  38. DBConnector::$queries[] = $sql.'; ('.round((microtime(true)-$time)*1000, 1).'ms)';
  39. }
  40. return $res;
  41. }
  42. /**
  43. * Выполняет запрос и возвращает объект результата
  44. *
  45. * @param string $sql
  46. * @return object
  47. */
  48. function query($sql)
  49. {
  50. $res = $this->exec($sql);
  51. switch (strtolower(substr($sql, 0, 6))) {
  52. case 'select':
  53. case '(selec':
  54. return new ModelSelectResult($res);
  55. case 'insert':
  56. case 'replac':
  57. return new ModelInsertResult($this->handler, $res); //$res for postgreSQL
  58. default:
  59. return new ModelChangeResult($this->handler, $res); //$res for postgreSQL
  60. }
  61. }
  62. /**
  63. * Экранирует строку
  64. *
  65. * @param mixed $data - строка для экранирования
  66. * @return mixed
  67. */
  68. function escape($data)
  69. {
  70. if(is_array($data)){
  71. foreach($data as $id => $val){
  72. $data[$id] = DBConnector::escape($this->handler, $val);
  73. }
  74. return $data;
  75. }
  76. return DBConnector::escape($this->handler, $data);
  77. }
  78. //////////////////////////
  79. function update($id, $data)
  80. {
  81. $sql = '';
  82. foreach ($data as $key => $val) {
  83. $sql .= $key."='".$this->escape($val)."', ";
  84. }
  85. return $this->query('UPDATE '.$this->table.' SET '.rtrim($sql, ', ').' WHERE '.$this->primary_key.'='.(int) $id);
  86. }
  87. function insert($data, $postfix = '')
  88. {
  89. $keys = array();
  90. $values = array();
  91. foreach ($data as $key => $val) {
  92. $keys[] = $key;
  93. $values[] = $this->escape($val);
  94. }
  95. return $this->query('INSERT INTO '.$this->table.' ('.implode(',', $keys).") VALUES('".implode("','", $values)."') ".$postfix);
  96. }
  97. function delete($id)
  98. {
  99. return $this->query('DELETE FROM '.$this->table.' WHERE '.$this->primary_key.'='.(int) $id);
  100. }
  101. function get($id)
  102. {
  103. return $this->query('SELECT * FROM '.$this->table.' WHERE '.$this->primary_key.'='.(int) $id);
  104. }
  105. function getList($limit = false, $sort = 'ASC')
  106. {
  107. return $this->query('SELECT *
  108. FROM '.$this->table.'
  109. ORDER BY '.$this->primary_key.' '.($sort == 'ASC' ? 'ASC' : 'DESC')
  110. .($limit !== false ? ' LIMIT '.(int) $limit : ''))->fetchAll();
  111. }
  112. function setAutocommit($set)
  113. {
  114. return DBConnector::autocommit($this->handler, (bool) $set);
  115. }
  116. function commit()
  117. {
  118. return DBConnector::commit($this->handler);
  119. }
  120. function rollback()
  121. {
  122. return DBConnector::rollback($this->handler);
  123. }
  124. }
  125. class ModelResult
  126. {
  127. function __call($name, $args)
  128. {
  129. throw new MJException('Call undeclared method "'.$name.'" in "'.get_class($this).'" class', -1);
  130. }
  131. }
  132. class ModelSelectResult extends ModelResult
  133. {
  134. public $result;
  135. function __construct($res)
  136. {
  137. $this->result = $res;
  138. }
  139. function fetch($class_name = false)
  140. {
  141. return DBConnector::fetchObject($this->result, $class_name);
  142. }
  143. function fetchField($field, $default = false)
  144. {
  145. $row = $this->fetch();
  146. return isset($row->$field) ? $row->$field : $default;
  147. }
  148. function fetchAll($key = false)
  149. {
  150. $array = array();
  151. if ($key) {
  152. while ($row = DBConnector::fetchObject($this->result)) {
  153. $array[$row->$key] = $row;
  154. }
  155. } else {
  156. while ($row = DBConnector::fetchObject($this->result)) {
  157. $array[] = $row;
  158. }
  159. }
  160. return $array;
  161. }
  162. /**
  163. * Fetches all SQL result rows as an array of key-value pairs.
  164. *
  165. * The first column is the key, the second column is the
  166. * value.
  167. *
  168. * @return array
  169. */
  170. public function fetchPairs()
  171. {
  172. if (!method_exists('DBConnector', 'fetchArray')) {
  173. throw new Exception('Method not implemented yet.');
  174. }
  175. $data = array();
  176. while ($row = DBConnector::fetchArray($this->result, DBConnector::FETCH_NUM)) {
  177. $data[$row[0]] = $row[1];
  178. }
  179. return $data;
  180. }
  181. function count()
  182. {
  183. return DBConnector::numRows($this->result);
  184. }
  185. function free()
  186. {
  187. DBConnector::free($this->result);
  188. }
  189. function __destruct() {
  190. $this->free();
  191. }
  192. }
  193. class ModelChangeResult extends ModelResult
  194. {
  195. public $affected;
  196. function __construct($resource, $result)
  197. {
  198. $this->affected = DBConnector::affectedRows($resource, $result);
  199. }
  200. function count()
  201. {
  202. return $this->affected;
  203. }
  204. }
  205. class ModelInsertResult extends ModelChangeResult
  206. {
  207. public $id;
  208. function __construct($resource, $result)
  209. {
  210. parent::__construct($resource, $result);
  211. $this->id = DBConnector::getId($resource);
  212. }
  213. function getId()
  214. {
  215. return $this->id;
  216. }
  217. }
  218. ?>