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.

210 lines
4.9 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. $time = microtime(true);
  31. $res = mysqli_query($this->handler, $sql);
  32. if (mysqli_errno($this->handler)) {
  33. throw new MJException("<b>Query Error:</b>\n".$sql."\n<b>Error:</b>\n".mysqli_error($this->handler), 1);
  34. }
  35. if (DEBUG_ENABLE) {
  36. DBConnector::$queries[] = $sql.'; ('.round((microtime(true)-$time)*1000, 1).'ms)';
  37. }
  38. return $res;
  39. }
  40. /**
  41. * Выполняет запрос и возвращает объект результата
  42. *
  43. * @param string $sql
  44. * @return object
  45. */
  46. function query($sql)
  47. {
  48. $res = $this->exec($sql);
  49. switch (strtolower(substr($sql, 0, 6))) {
  50. case 'select':
  51. case '(selec':
  52. return new ModelSelectResult($res);
  53. case 'insert':
  54. case 'replac':
  55. return new ModelInsertResult($this->handler);
  56. default:
  57. return new ModelChangeResult($this->handler);
  58. }
  59. }
  60. /**
  61. * Экранирует строку
  62. *
  63. * @param mixed $data - строка для экранирования
  64. * @return mixed
  65. */
  66. function escape($data)
  67. {
  68. if(is_array($data)){
  69. foreach($data as $id => $val){
  70. $data[$id] = mysqli_real_escape_string($this->handler, $val);
  71. }
  72. return $data;
  73. }
  74. return mysqli_real_escape_string($this->handler, $data);
  75. }
  76. //////////////////////////
  77. function update($id, $data)
  78. {
  79. $sql = '';
  80. foreach ($data as $key => $val) {
  81. $sql .= $key."='".$this->escape($val)."', ";
  82. }
  83. return $this->query('UPDATE '.$this->table.' SET '.rtrim($sql, ', ').' WHERE '.$this->primary_key.'='.(int) $id);
  84. }
  85. function insert($data, $postfix = '')
  86. {
  87. $sql = '';
  88. foreach ($data as $key => $val) {
  89. $sql .= $key.'="'.$this->escape($val).'", ';
  90. }
  91. return $this->query('INSERT '.$this->table.' SET '.rtrim($sql, ', ').' '.$postfix);
  92. }
  93. function delete($id)
  94. {
  95. return $this->query('DELETE FROM '.$this->table.' WHERE '.$this->primary_key.'='.(int) $id);
  96. }
  97. function get($id)
  98. {
  99. return $this->query('SELECT * FROM '.$this->table.' WHERE '.$this->primary_key.'='.(int) $id);
  100. }
  101. function getList($limit = false, $sort = 'ASC')
  102. {
  103. return $this->query('SELECT *
  104. FROM '.$this->table.'
  105. ORDER BY '.$this->primary_key.' '.($sort == 'ASC' ? 'ASC' : 'DESC')
  106. .($limit !== false ? ' LIMIT '.(int) $limit : ''))->fetchAll();
  107. }
  108. }
  109. class ModelResult
  110. {
  111. function __call($name, $args)
  112. {
  113. throw new MJException('Call undeclared method "'.$name.'" in "'.get_class($this).'" class', -1);
  114. }
  115. }
  116. class ModelSelectResult extends ModelResult
  117. {
  118. public $result;
  119. function __construct($res)
  120. {
  121. $this->result = $res;
  122. }
  123. function fetch($class_name = false)
  124. {
  125. return $class_name ? mysqli_fetch_object($this->result, $class_name) : mysqli_fetch_object($this->result);
  126. }
  127. function fetchField($field, $default = false)
  128. {
  129. $row = $this->fetch();
  130. return isset($row->$field) ? $row->$field : $default;
  131. }
  132. function fetchAll($key = false)
  133. {
  134. $array = array();
  135. if ($key) {
  136. while ($row = mysqli_fetch_object($this->result)) {
  137. $array[$row->$key] = $row;
  138. }
  139. } else {
  140. while ($row = mysqli_fetch_object($this->result)) {
  141. $array[] = $row;
  142. }
  143. }
  144. return $array;
  145. }
  146. function count()
  147. {
  148. return mysqli_num_rows($this->result);
  149. }
  150. function free()
  151. {
  152. mysqli_free_result($this->result);
  153. }
  154. function __destruct() {
  155. $this->free();
  156. }
  157. }
  158. class ModelChangeResult extends ModelResult
  159. {
  160. public $affected;
  161. function __construct($resource)
  162. {
  163. $this->affected = mysqli_affected_rows($resource);
  164. }
  165. function count()
  166. {
  167. return $this->affected;
  168. }
  169. }
  170. class ModelInsertResult extends ModelChangeResult
  171. {
  172. public $id;
  173. function __construct($resource)
  174. {
  175. parent::__construct($resource);
  176. $this->id = mysqli_insert_id($resource);
  177. }
  178. function getId()
  179. {
  180. return $this->id;
  181. }
  182. }
  183. ?>