Database.class.php 2.1 KB

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