Entity.class.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. <?php
  2. require_once dirname(__FILE__).'/../constant.php';
  3. /**
  4. @version 2
  5. **/
  6. class Entity
  7. {
  8. public $debug = false,$pdo = null;
  9. public static $lastError = '';
  10. public static $lastQuery = '';
  11. public function __construct()
  12. {
  13. $this->connect();
  14. }
  15. public function connect()
  16. {
  17. $this->pdo = Database::instance();
  18. if (!isset($this->TABLE_NAME)) {
  19. $this->TABLE_NAME = strtolower(get_called_class());
  20. }
  21. }
  22. public function __toString()
  23. {
  24. foreach ($this->toArray() as $key => $value) {
  25. echo $key.' : '.$value.','.PHP_EOL;
  26. }
  27. }
  28. public static function debug()
  29. {
  30. return array(self::$lastQuery, self::$lastError);
  31. }
  32. public function __sleep()
  33. {
  34. return array_keys($this->toArray());
  35. }
  36. public function __wakeup()
  37. {
  38. $this->connect();
  39. }
  40. public function toArray()
  41. {
  42. $fields = array();
  43. foreach ($this->fields as $field => $type) {
  44. $fields[$field] = $this->$field;
  45. }
  46. return $fields;
  47. }
  48. public function fromArray($array)
  49. {
  50. foreach ($array as $field => $value) {
  51. $this->$field = $value;
  52. }
  53. }
  54. public function sgbdType($type)
  55. {
  56. $types = array();
  57. $types['string'] = $types['timestamp'] = $types['date'] = 'VARCHAR(255)';
  58. $types['longstring'] = 'TEXT';
  59. $types['key'] = 'INTEGER NOT NULL PRIMARY KEY';
  60. $types['object'] = $types['integer'] = 'bigint(20)';
  61. $types['boolean'] = 'INTEGER(1)';
  62. $types['blob'] = ' BLOB';
  63. $types['default'] = 'TEXT';
  64. return isset($types[$type]) ? $types[$type] : $types['default'];
  65. }
  66. public function closeDatabase()
  67. {
  68. //$this->close();
  69. }
  70. public static function tableName()
  71. {
  72. $class = get_called_class();
  73. $instance = new $class();
  74. return ENTITY_PREFIX.$instance->TABLE_NAME;
  75. }
  76. // GESTION SQL
  77. /**
  78. * Verifie l'existence de la table en base de donnée.
  79. *
  80. * @author Valentin CARRUESCO
  81. *
  82. * @category manipulation SQL
  83. *
  84. * @param <String> créé la table si elle n'existe pas
  85. *
  86. * @return true si la table existe, false dans le cas contraire
  87. */
  88. public static function checkTable($autocreate = false)
  89. {
  90. $class = get_called_class();
  91. $instance = new $class();
  92. $query = 'SELECT count(*) as numRows FROM sqlite_master WHERE type="table" AND name=?';
  93. $statement = $instance->customQuery($query, array($instance->tableName()));
  94. if ($statement != false) {
  95. $statement = $statement->fetchArray();
  96. if ($statement['numRows'] == 1) {
  97. $return = true;
  98. }
  99. }
  100. if ($autocreate && !$return) {
  101. self::create();
  102. }
  103. return $return;
  104. }
  105. public static function install($classDirectory)
  106. {
  107. foreach (glob($classDirectory.DIRECTORY_SEPARATOR.'*.class.php') as $file) {
  108. $infos = explode('.', basename($file));
  109. $class = array_shift($infos);
  110. if (!class_exists($class) || !method_exists($class, 'create') || $class == get_class()) {
  111. continue;
  112. }
  113. $class::create();
  114. }
  115. }
  116. /**
  117. * Methode de creation de l'entité.
  118. *
  119. * @author Valentin CARRUESCO
  120. *
  121. * @category manipulation SQL
  122. *
  123. * @return Aucun retour
  124. */
  125. public static function create()
  126. {
  127. $class = get_called_class();
  128. $instance = new $class();
  129. $query = 'CREATE TABLE IF NOT EXISTS `'.ENTITY_PREFIX.$instance->TABLE_NAME.'` (';
  130. foreach ($instance->fields as $field => $type) {
  131. $query .= '`'.$field.'` '.$instance->sgbdType($type).' ,';
  132. }
  133. $query = substr($query, 0, strlen($query) - 1);
  134. $query .= ');';
  135. $instance->customExecute($query);
  136. }
  137. public static function drop()
  138. {
  139. $class = get_called_class();
  140. $instance = new $class();
  141. $query = 'DROP TABLE `'.$instance->tableName().'`;';
  142. $instance->customExecute($query);
  143. }
  144. /**
  145. * Methode d'insertion ou de modifications d'elements de l'entité.
  146. *
  147. * @author Valentin CARRUESCO
  148. *
  149. * @category manipulation SQL
  150. *
  151. * @param Aucun
  152. *
  153. * @return Aucun retour
  154. */
  155. public function save()
  156. {
  157. $data = array();
  158. if (isset($this->id) && $this->id > 0) {
  159. $query = 'UPDATE `'.ENTITY_PREFIX.$this->TABLE_NAME.'` SET ';
  160. foreach ($this->fields as $field => $type) {
  161. $value = $this->{$field};
  162. $query .= '`'.$field.'`=?,';
  163. $data[] = $value;
  164. }
  165. $query = substr($query, 0, strlen($query) - 1);
  166. $data[] = $this->id;
  167. $query .= ' WHERE `id`=?;';
  168. } else {
  169. $query = 'INSERT INTO `'.$this->tableName().'`(';
  170. foreach ($this->fields as $field => $type) {
  171. if ($type != 'key') {
  172. $query .= '`'.$field.'`,';
  173. }
  174. }
  175. $query = substr($query, 0, strlen($query) - 1);
  176. $query .= ')VALUES(';
  177. foreach ($this->fields as $field => $type) {
  178. if ($type == 'key') {
  179. continue;
  180. }
  181. $query .= '?,';
  182. $data[] = $this->{$field};
  183. }
  184. $query = substr($query, 0, strlen($query) - 1);
  185. $query .= ');';
  186. }
  187. $this->customExecute($query, $data);
  188. $this->id = (!isset($this->id) || !(is_numeric($this->id)) ? $this->pdo->lastInsertId() : $this->id);
  189. }
  190. /**
  191. * Méthode de modification d'éléments de l'entité.
  192. *
  193. * @author Valentin CARRUESCO
  194. *
  195. * @category manipulation SQL
  196. *
  197. * @param <Array> $colonnes=>$valeurs
  198. * @param <Array> $colonnes (WHERE) =>$valeurs (WHERE)
  199. * @param <String> $operation="=" definis le type d'operateur pour la requete select
  200. *
  201. * @return Aucun retour
  202. */
  203. public static function change($columns, $columns2 = null, $operation = '=')
  204. {
  205. $class = get_called_class();
  206. $instance = new $class();
  207. $data = array();
  208. $query = 'UPDATE `'.$instance->tableName().'` SET ';
  209. foreach ($columns as $column => $value) {
  210. $query .= '`'.$column.'`=?,';
  211. $data[] = $value;
  212. }
  213. $query = substr($query, 0, strlen($query) - 1);
  214. if ($columns2 != null) {
  215. $query .= ' WHERE ';
  216. foreach ($columns2 as $column => $value) {
  217. $query .= '`'.$column.'`'.$operation.'?,';
  218. $data[] = $value;
  219. }
  220. $query = substr($query, 0, strlen($query) - 1);
  221. }
  222. $instance->customExecute($query, $data);
  223. }
  224. /**
  225. * Méthode de selection de tous les elements de l'entité.
  226. *
  227. * @author Valentin CARRUESCO
  228. *
  229. * @category manipulation SQL
  230. *
  231. * @param <String> $ordre=null
  232. * @param <String> $limite=null
  233. *
  234. * @return <Array<Entity>> $Entity
  235. */
  236. public static function populate($order = null, $limit = null)
  237. {
  238. $results = self::loadAll(array(), $order, $limit, '=');
  239. return $results;
  240. }
  241. /**
  242. * Méthode de selection multiple d'elements de l'entité.
  243. *
  244. * @author Valentin CARRUESCO
  245. *
  246. * @category manipulation SQL
  247. *
  248. * @param <Array> $colonnes (WHERE)
  249. * @param <Array> $valeurs (WHERE)
  250. * @param <String> $ordre=null
  251. * @param <String> $limite=null
  252. * @param <String> $operation="=" definis le type d'operateur pour la requete select
  253. *
  254. * @return <Array<Entity>> $Entity
  255. */
  256. public static function loadAll($columns = array(), $order = null, $limit = null, $operation = '=', $selColumn = '*')
  257. {
  258. $objects = array();
  259. $whereClause = '';
  260. $data = array();
  261. if ($columns != null && sizeof($columns) != 0) {
  262. $whereClause .= ' WHERE ';
  263. $i = false;
  264. foreach ($columns as $column => $value) {
  265. if ($i) {
  266. $whereClause .= ' AND ';
  267. } else {
  268. $i = true;
  269. }
  270. $whereClause .= '`'.$column.'`'.$operation.'?';
  271. $data[] = $value;
  272. }
  273. }
  274. $class = get_called_class();
  275. $instance = new $class();
  276. $query = 'SELECT '.$selColumn.' FROM `'.$instance->tableName().'` '.$whereClause.' ';
  277. if ($order != null) {
  278. $query .= 'ORDER BY '.$order.' ';
  279. }
  280. if ($limit != null) {
  281. $query .= 'LIMIT '.$limit.' ';
  282. }
  283. $query .= ';';
  284. return $instance->customQuery($query, $data, true);
  285. }
  286. public static function loadAllOnlyColumn($selColumn, $columns, $order = null, $limit = null, $operation = '=')
  287. {
  288. $objects = self::loadAll($columns, $order, $limit, $operation, $selColumn);
  289. if (count($objects) == 0) {
  290. $objects = array();
  291. }
  292. return $objects;
  293. }
  294. /**
  295. * Méthode de selection unique d'élements de l'entité.
  296. *
  297. * @author Valentin CARRUESCO
  298. *
  299. * @category manipulation SQL
  300. *
  301. * @param <Array> $colonnes (WHERE)
  302. * @param <Array> $valeurs (WHERE)
  303. * @param <String> $operation="=" definis le type d'operateur pour la requete select
  304. *
  305. * @return <Entity> $Entity ou false si aucun objet n'est trouvé en base
  306. */
  307. public static function load($columns, $operation = '=')
  308. {
  309. $objects = self::loadAll($columns, null, '1', $operation);
  310. if (!isset($objects[0])) {
  311. $objects[0] = false;
  312. }
  313. return $objects[0];
  314. }
  315. /**
  316. * Méthode de selection unique d'élements de l'entité.
  317. *
  318. * @author Valentin CARRUESCO
  319. *
  320. * @category manipulation SQL
  321. *
  322. * @param <Array> $colonnes (WHERE)
  323. * @param <Array> $valeurs (WHERE)
  324. * @param <String> $operation="=" definis le type d'operateur pour la requete select
  325. *
  326. * @return <Entity> $Entity ou false si aucun objet n'est trouvé en base
  327. */
  328. public static function getById($id, $operation = '=')
  329. {
  330. return self::load(array('id' => $id), $operation);
  331. }
  332. /**
  333. * Methode de comptage des éléments de l'entité.
  334. *
  335. * @author Valentin CARRUESCO
  336. *
  337. * @category manipulation SQL
  338. * @return<Integer> nombre de ligne dans l'entité'
  339. */
  340. public static function rowCount($columns = null)
  341. {
  342. $class = get_called_class();
  343. $instance = new $class();
  344. $whereClause = '';
  345. $data = array();
  346. if ($columns != null) {
  347. $whereClause = ' WHERE ';
  348. $i = false;
  349. foreach ($columns as $column => $value) {
  350. if ($i) {
  351. $whereClause .= ' AND ';
  352. } else {
  353. $i = true;
  354. }
  355. $whereClause .= '`'.$column.'`=?';
  356. $data[] = $value;
  357. }
  358. }
  359. $query = 'SELECT COUNT(id) resultNumber FROM '.$instance->tableName().$whereClause;
  360. $execQuery = $instance->customQuery($query, $data);
  361. $row = $execQuery->fetch();
  362. return $row['resultNumber'];
  363. }
  364. /**
  365. * Methode de définition de l'éxistence d'un moins un des éléments spécifiés en base.
  366. *
  367. * @author Valentin CARRUESCO
  368. *
  369. * @category manipulation SQL
  370. * @return<boolean> existe (true) ou non (false)
  371. */
  372. public static function exist($columns = null)
  373. {
  374. $result = self::rowCount($columns);
  375. return $result != 0;
  376. }
  377. public static function deleteById($id)
  378. {
  379. self::delete(array('id' => $id));
  380. }
  381. /**
  382. * Méthode de supression d'elements de l'entité.
  383. *
  384. * @author Valentin CARRUESCO
  385. *
  386. * @category manipulation SQL
  387. *
  388. * @param <Array> $colonnes (WHERE)
  389. * @param <Array> $valeurs (WHERE)
  390. * @param <String> $operation="=" definis le type d'operateur pour la requete select
  391. *
  392. * @return Aucun retour
  393. */
  394. public static function delete($columns, $operation = '=', $limit = null)
  395. {
  396. $class = get_called_class();
  397. $instance = new $class();
  398. $whereClause = '';
  399. $i = false;
  400. $data = array();
  401. foreach ($columns as $column => $value) {
  402. if ($i) {
  403. $whereClause .= ' AND ';
  404. } else {
  405. $i = true;
  406. }
  407. $whereClause .= '`'.$column.'`'.$operation.'?';
  408. $data[] = $value;
  409. }
  410. $query = 'DELETE FROM `'.ENTITY_PREFIX.$instance->TABLE_NAME.'` WHERE '.$whereClause.' '.(isset($limit) ? 'LIMIT '.$limit : '').';';
  411. $instance->customExecute($query, $data);
  412. }
  413. public function customExecute($query, $data = array())
  414. {
  415. self::$lastQuery = $query;
  416. $stm = $this->pdo->prepare($query);
  417. try {
  418. $stm->execute($data);
  419. } catch (Exception $e) {
  420. self::$lastError = $this->pdo->errorInfo();
  421. throw new Exception($e->getMessage());
  422. }
  423. }
  424. public static function staticQuery($query, $data = array(), $fill = false)
  425. {
  426. $class = get_called_class();
  427. $instance = new $class();
  428. return $instance->customQuery($query, $data, $fill);
  429. }
  430. public function customQuery($query, $data = array(), $fill = false)
  431. {
  432. self::$lastQuery = $query;
  433. $results = $this->pdo->prepare($query);
  434. $results->execute($data);
  435. if (!$results) {
  436. self::$lastError = $this->pdo->errorInfo();
  437. return false;
  438. } else {
  439. if (!$fill) {
  440. return $results;
  441. }
  442. $class = get_class($this);
  443. $objects = array();
  444. while ($queryReturn = $results->fetch()) {
  445. $object = new $class();
  446. foreach ($this->fields as $field => $type) {
  447. if (isset($queryReturn[$field])) {
  448. $object->{$field} = $queryReturn[$field];
  449. }
  450. }
  451. $objects[] = $object;
  452. unset($object);
  453. }
  454. return $objects == null ? array() : $objects;
  455. }
  456. }
  457. public function __get($name)
  458. {
  459. $pos = strpos($name, '_object');
  460. if ($pos !== false) {
  461. $field = strtolower(substr($name, 0, $pos));
  462. if (array_key_exists($field, $this->fields)) {
  463. $class = ucfirst($field);
  464. return $class::getById($this->{$field});
  465. }
  466. }
  467. throw new Exception('Attribut '.get_class($this)."->$name non existant");
  468. }
  469. }