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.

230 lines
5.3 KiB

  1. <?php
  2. /**
  3. * Класс модели данных
  4. *
  5. * @copyright
  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);
  58. default:
  59. return new ModelChangeResult($this->handler);
  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. function count()
  163. {
  164. return DBConnector::numRows($this->result);
  165. }
  166. function free()
  167. {
  168. DBConnector::free($this->result);
  169. }
  170. function __destruct() {
  171. $this->free();
  172. }
  173. }
  174. class ModelChangeResult extends ModelResult
  175. {
  176. public $affected;
  177. function __construct($resource)
  178. {
  179. $this->affected = DBConnector::affectedRows($resource);
  180. }
  181. function count()
  182. {
  183. return $this->affected;
  184. }
  185. }
  186. class ModelInsertResult extends ModelChangeResult
  187. {
  188. public $id;
  189. function __construct($resource)
  190. {
  191. parent::__construct($resource);
  192. $this->id = DBConnector::getId($resource);
  193. }
  194. function getId()
  195. {
  196. return $this->id;
  197. }
  198. }
  199. ?>