Database.class.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. require_once(dirname(__DIR__).DIRECTORY_SEPARATOR.'constant.php');
  3. /**
  4. * PDO Connector for database connexion.
  5. *
  6. * @author v.carruesco
  7. *
  8. * @category Core
  9. *
  10. * @license MIT
  11. */
  12. class Database {
  13. public $connections = array();
  14. public static $instance = null;
  15. private function __construct() {
  16. $this->connect();
  17. }
  18. /**
  19. * Methode de recuperation unique de l'instance.
  20. * @author Valentin CARRUESCO
  21. * @category Singleton
  22. * @param <Aucun>
  23. * @return <pdo> $instance
  24. */
  25. public static function instance($baseuid) {
  26. if (self::$instance === null)
  27. self::$instance = new self();
  28. if(!isset(self::$instance->connections[$baseuid]))
  29. self::$instance->connect($baseuid);
  30. return self::$instance->connections[$baseuid];
  31. }
  32. public static function version($baseUid = 'local'){
  33. try {
  34. $db = new self();
  35. $db->connect();
  36. return $db->connections[$baseUid]->getAttribute(PDO::ATTR_SERVER_VERSION);
  37. } catch (Exception $e) {
  38. return 'Connection à la base impossible : '. $e->getMessage();
  39. }
  40. }
  41. public function connect($baseUid = 'local') {
  42. try {
  43. global $databases_credentials;
  44. $database = $databases_credentials[$baseUid];
  45. $connector = $database['connector'];
  46. require_once(__ROOT__.'connector/'.$connector.'.class.php');
  47. $connectionString = $connector::connection;
  48. foreach ($database as $key => $value) {
  49. $connectionString = str_replace('{{'.$key.'}}',$value,$connectionString);
  50. }
  51. $connectionString = str_replace('{{ROOT}}',__ROOT__,$connectionString);
  52. $this->connections[$baseUid] = new PDO($connectionString, $database['login'], $database['password'],$connector::pdo_attributes());
  53. if(method_exists ( $connector , 'beforeTransaction' ))
  54. $connector::beforeTransaction($this->connections[$baseUid]);
  55. } catch (Exception $e) {
  56. echo 'Connection à la base impossible : ', $e->getMessage();
  57. die();
  58. }
  59. }
  60. }