AbstractTable.php 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. <?php
  2. namespace Ipol\DPD\DB;
  3. /**
  4. * Абстрактный класс реализующий взаимодействие с одной таблицей
  5. */
  6. abstract class AbstractTable implements TableInterface
  7. {
  8. protected $connection;
  9. /**
  10. * Конструктор класса
  11. *
  12. * @param \Ipol\DPD\DB\ConnectionInterface
  13. */
  14. public function __construct(ConnectionInterface $connection)
  15. {
  16. $this->connection = $connection;
  17. }
  18. /**
  19. * Возвращает соединение с БД
  20. *
  21. * @return \Ipol\DPD\DB\ConnectionInterface
  22. */
  23. public function getConnection()
  24. {
  25. return $this->connection;
  26. }
  27. /**
  28. * Возвращает конфиг
  29. *
  30. * @return \Ipol\DPD\Config\ConfigInterface
  31. */
  32. public function getConfig()
  33. {
  34. return $this->getConnection()->getConfig();
  35. }
  36. /**
  37. * Возвращает инстанс PDO
  38. *
  39. * @return \PDO
  40. */
  41. public function getPDO()
  42. {
  43. return $this->getConnection()->getPDO();
  44. }
  45. /**
  46. * Возвращает имя класса модели
  47. *
  48. * @return array
  49. */
  50. public function getModelClass()
  51. {
  52. return \Ipol\DPD\DB\Model::class;
  53. }
  54. /**
  55. * Возвращает инстанс модели ассоциированной с таблицой
  56. *
  57. * @return \Ipol\DPD\DB\Model
  58. */
  59. public function makeModel($id = false)
  60. {
  61. $classname = $this->getModelClass();
  62. return new $classname($this, $id);
  63. }
  64. /**
  65. * Создание таблицы при необходимости
  66. *
  67. * @return void
  68. */
  69. public function checkTableSchema()
  70. {
  71. $sqlPath = sprintf('%s/db/install/%s/%s.sql',
  72. $this->getConfig()->get('DATA_DIR'),
  73. $this->getConnection()->getDriver(),
  74. $this->getTableName()
  75. );
  76. if (file_exists($sqlPath)) {
  77. $sql = file_get_contents($sqlPath);
  78. $this->getPDO()->query($sql);
  79. }
  80. }
  81. /**
  82. * Добавление записи
  83. *
  84. * @param array $values
  85. *
  86. * @return bool
  87. */
  88. public function add($values)
  89. {
  90. $fields = array_keys($values);
  91. $values = $this->prepareParms($values);
  92. $placeholders = array_keys($values);
  93. $sql = 'INSERT INTO '
  94. . $this->getTableName()
  95. . ' ('. implode(',', $fields) .') VALUES ('
  96. . implode(',', $placeholders) .')'
  97. ;
  98. return $this->getPDO()
  99. ->prepare($sql)
  100. ->execute($values)
  101. ? $this->getPDO()->lastInsertId()
  102. : false;
  103. }
  104. /**
  105. * Обновление записи
  106. *
  107. * @param int $id
  108. * @param array $values
  109. *
  110. * @return bool
  111. */
  112. public function update($id, $values)
  113. {
  114. $fields = array_keys($values);
  115. $values = $this->prepareParms($values);
  116. $placeholders = array_keys($values);
  117. $sql = 'UPDATE '. $this->getTableName() .' SET ';
  118. foreach ($fields as $i => $field) {
  119. $sql .= $field .'='. $placeholders[$i] .',';
  120. }
  121. $sql = trim($sql, ',') . ' WHERE id = :id_where';
  122. return $this->getPDO()
  123. ->prepare($sql)
  124. ->execute(array_merge(
  125. $values,
  126. [':id_where' => $id]
  127. ));
  128. }
  129. /**
  130. * Удаление записи
  131. *
  132. * @param int $id
  133. *
  134. * @return bool
  135. */
  136. public function delete($id)
  137. {
  138. $sql = 'DELETE FROM '. $this->getTableName .' WHERE id = :id';
  139. return $this->getPDO()
  140. ->prepare($sql)
  141. ->execute([':id' => $id]);
  142. }
  143. /**
  144. * Выборка записей
  145. *
  146. * $parms = "id = 1" or
  147. * $parms = [
  148. * 'select' => '*',
  149. * 'where' => 'id = :id',
  150. * 'order' => 'id asc',
  151. * 'limit' => '0,1',
  152. * 'bind' => [':id' => 1]
  153. * ]
  154. *
  155. * @param string|array $parms
  156. *
  157. * @return \PDOStatement
  158. */
  159. public function find($parms = [])
  160. {
  161. $parms = is_array($parms)
  162. ? $parms
  163. : [
  164. 'where' => $parms,
  165. ]
  166. ;
  167. $sql = sprintf('SELECT %s FROM %s %s %s %s',
  168. isset($parms['select']) ? $parms['select'] : '*',
  169. $this->getTableName(),
  170. isset($parms['where']) ? "WHERE {$parms['where']}" : '',
  171. isset($parms['order']) ? "ORDER BY {$parms['order']}" : '',
  172. isset($parms['limit']) ? "LIMIT {$parms['limit']}" : ''
  173. );
  174. $query = $this->getPDO()->prepare($sql);
  175. return $query->execute($parms['bind'])
  176. ? $query
  177. : false
  178. ;
  179. }
  180. /**
  181. * Выборка одной записи, псевдномим над find limit 0,1
  182. *
  183. * @param int|string|array $parms
  184. *
  185. * @return array
  186. */
  187. public function findFirst($parms = [])
  188. {
  189. if (is_numeric($parms)) {
  190. $parms = ['where' => 'id = :id', 'bind' => ['id' => $parms]];
  191. } elseif (is_string($parms)) {
  192. $parms = ['where' => $parms];
  193. }
  194. $parms['limit'] = '0,1';
  195. return $this->find($parms)->fetch();
  196. }
  197. /**
  198. * Составляет массив bind-values для передачи в PDO
  199. *
  200. * @param array $parms
  201. *
  202. * @return array
  203. */
  204. protected function prepareParms($parms)
  205. {
  206. $ret = array();
  207. foreach ($parms as $k => $v) {
  208. $ret[':'. $k] = $v;
  209. }
  210. return $ret;
  211. }
  212. }