/framework/libraries/Model.php

https://github.com/PHPhackathon/Bublr · PHP · 296 lines · 149 code · 24 blank · 123 comment · 9 complexity · 96e74b007d30d0010df85227f110b7ed MD5 · raw file

  1. <?php
  2. /****************************************************
  3. * Lean mean web machine
  4. *
  5. * Base model library
  6. *
  7. * @author Dirk Bonhomme <dirk@bytelogic.be>
  8. * @created 2010-10-18
  9. *
  10. ****************************************************/
  11. class Model
  12. {
  13. protected $table = null;
  14. protected $primaryKey = 'id';
  15. /**
  16. * Get all records by query and optional params
  17. *
  18. * @param string $query
  19. * @param array $param1 optional. Values [$parameter, $value, $data_type]
  20. * @param array $param2 optional
  21. * @param ...
  22. * @return array
  23. */
  24. public function getAll($query, $param1 = null){
  25. // Execute statement
  26. $parameters = func_get_args();
  27. $parameters = array_filter($parameters);
  28. $parametersCount = count($parameters);
  29. if($parametersCount > 1){
  30. $statement = Database::instance()->prepare($query);
  31. for($i = 1; $i < $parametersCount; $i++){
  32. $statement->bindValue(
  33. $parameters[$i][0],
  34. $parameters[$i][1],
  35. $parameters[$i][2]
  36. );
  37. }
  38. $statement->execute();
  39. }else{
  40. $statement = Database::instance()->query($query);
  41. }
  42. // Return array with results
  43. $results = array();
  44. $statement->setFetchMode(PDO::FETCH_ASSOC);
  45. while($result = $statement->fetch()){
  46. array_push($results, $result);
  47. }
  48. return $results;
  49. }
  50. /**
  51. * Get one record by query and optional params
  52. *
  53. * @param string $query
  54. * @param array $param1 optional. Values [$parameter, $value, $data_type]
  55. * @param array $param2 optional
  56. * @param ...
  57. * @return array
  58. */
  59. public function getRecord($query, $param1 = null){
  60. $parameters = func_get_args();
  61. $records = call_user_func_array(array($this, 'getAll'), $parameters);
  62. return array_shift($records);
  63. }
  64. /**
  65. * Get one field by query and optional params
  66. *
  67. * @param string $query
  68. * @param array $param1 optional. Values [$parameter, $value, $data_type]
  69. * @param array $param2 optional
  70. * @param ...
  71. * @return mixed
  72. */
  73. public function getField($query, $param1 = null){
  74. $parameters = func_get_args();
  75. $records = call_user_func_array(array($this, 'getAll'), $parameters);
  76. $record = array_shift($records);
  77. return $record? array_shift($record) : null;
  78. }
  79. /**
  80. * Get records by query and optional params
  81. * Use first key as array key. If there are only two elements for each record,
  82. * return one-dimensional array as result
  83. *
  84. * @param string $query
  85. * @param array $param1 optional. Values [$parameter, $value, $data_type]
  86. * @param array $param2 optional
  87. * @param ...
  88. * @return array
  89. */
  90. public function getAssoc($query, $param1 = null){
  91. $parameters = func_get_args();
  92. $recordsRaw = call_user_func_array(array($this, 'getAll'), $parameters);
  93. $records = array();
  94. if(count($recordsRaw) > 0){
  95. $keys = array_keys($recordsRaw[0]);
  96. $shiftResult = (count($keys) == 2);
  97. $key = $keys[0];
  98. foreach($recordsRaw as &$record){
  99. if($shiftResult){
  100. $records[$record[$key]] = $record[$keys[1]];
  101. }else{
  102. $records[$record[$key]] = $record;
  103. }
  104. }
  105. unset($record);
  106. }
  107. return $records;
  108. }
  109. /**
  110. * Get record by field name and value
  111. *
  112. * @param string $field
  113. * @param string $value
  114. * @notice Make sure $field is valid
  115. * @return array
  116. */
  117. public function getRecordByFieldValue($field, $value){
  118. $query = "SELECT * FROM `{$this->table}` WHERE `{$field}` = :value";
  119. return $this->getRecord($query,
  120. array(':value', $value, Database::PARAM_STR)
  121. );
  122. }
  123. /**
  124. * Get record by primary key value
  125. *
  126. * @param int $value
  127. * @return array
  128. */
  129. public function get($value){
  130. $query = "SELECT * FROM `{$this->table}` WHERE `{$this->primaryKey}` = :value";
  131. return $this->getRecord($query,
  132. array(':value', $value, Database::PARAM_INT)
  133. );
  134. }
  135. /**
  136. * Insert or update record
  137. *
  138. * @param array $data
  139. * @return int $recordId
  140. */
  141. public function save($data){
  142. if(isset($data[$this->primaryKey])){
  143. return $this->update($data);
  144. }else{
  145. return $this->insert($data);
  146. }
  147. }
  148. /**
  149. * Update existing record
  150. *
  151. * @param array $data
  152. * @return int $recordId
  153. */
  154. public function update($data){
  155. // Gather fields and data to update
  156. $updateValues = array();
  157. foreach(array_keys($data) as $field){
  158. array_push($updateValues, sprintf('`%1$s` = ?', $field));
  159. }
  160. // Execute update statement
  161. $query = sprintf(
  162. 'UPDATE `%1$s` SET %2$s WHERE `%3$s` = ?',
  163. $this->table,
  164. implode(',', $updateValues),
  165. $this->primaryKey
  166. );
  167. array_push($data, $data[$this->primaryKey]);
  168. Database::instance()->prepare($query)->execute(array_values($data));
  169. // Return updated id
  170. return $data[$this->primaryKey];
  171. }
  172. /**
  173. * Insert new record
  174. *
  175. * @param array $data
  176. * @return int $recordId
  177. */
  178. public function insert($data){
  179. // Execute insert statement
  180. $query = sprintf(
  181. 'INSERT INTO `%1$s` (`%2$s`) VALUES (%3$s)',
  182. $this->table,
  183. implode('`,`', array_keys($data)),
  184. implode(',', array_fill(0, count($data), '?'))
  185. );
  186. Database::instance()->prepare($query)->execute(array_values($data));
  187. // Return new id
  188. return Database::instance()->lastInsertId();
  189. }
  190. /**
  191. * Update sequence for given primary keys
  192. *
  193. * @param array $ids
  194. * @param string $field optional
  195. * @return void
  196. */
  197. public function updateSequence($ids, $field = 'sequence'){
  198. $query = "UPDATE `{$this->table}` SET `{$field}` = ? WHERE `{$this->primaryKey}` = ?";
  199. $statement = Database::instance()->prepare($query);
  200. for($i = 1; $i <= count($ids); $i++){
  201. $statement->execute(array($i, $ids[$i-1]));
  202. }
  203. unset($statement);
  204. }
  205. /**
  206. * Get highest sequence + 1
  207. *
  208. * @param string $field optional
  209. * @return int
  210. */
  211. public function getNextSequence($field = 'sequence'){
  212. $query = "SELECT MAX(`{$field}`) FROM {$this->table} LIMIT 1";
  213. return (intval($this->getField($query)) + 1);
  214. }
  215. /**
  216. * Execute query and optional params. Return affected rows.
  217. *
  218. * @param string $query
  219. * @param array $param1 optional. Values [$parameter, $value, $data_type]
  220. * @param array $param2 optional
  221. * @param ...
  222. * @return int
  223. */
  224. public function execute($query, $param1 = null){
  225. // Execute statement
  226. $parameters = func_get_args();
  227. $parametersCount = count($parameters);
  228. if($parametersCount > 1){
  229. $statement = Database::instance()->prepare($query);
  230. for($i = 1; $i < $parametersCount; $i++){
  231. $statement->bindValue(
  232. $parameters[$i][0],
  233. $parameters[$i][1],
  234. $parameters[$i][2]
  235. );
  236. }
  237. $statement->execute();
  238. return $statement->rowCount();
  239. }else{
  240. return Database::instance()->exec($query);
  241. }
  242. }
  243. /**
  244. * Delete record
  245. *
  246. * @param int $primaryKeyValue
  247. * @return void
  248. */
  249. public function delete($primaryKeyValue){
  250. $this->execute(
  251. sprintf('DELETE FROM `%1$s` WHERE `%2$s` = :value', $this->table, $this->primaryKey),
  252. array(':value', $primaryKeyValue, Database::PARAM_STR)
  253. );
  254. }
  255. /**
  256. * Delete records by field name and value
  257. *
  258. * @param string $field
  259. * @param string $value
  260. * @notice Make sure $field is valid
  261. * @return void
  262. */
  263. public function deleteByFieldValue($field, $value){
  264. $records = $this->getAll(
  265. sprintf('SELECT `%1$s` FROM `%2$s` WHERE `%3$s` = :value', $this->primaryKey, $this->table, $field),
  266. array(':value', $value, Database::PARAM_STR)
  267. );
  268. foreach($records as $record){
  269. $this->delete($record[$this->primaryKey]);
  270. }
  271. }
  272. }