Database.class.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. $connectionString = str_replace('{{ROOT}}',__ROOT__,$connectionString);
  51. $this->connections[$baseUid] = new PDO($connectionString, $database['login'], $database['password'],$connector::pdo_attributes());
  52. if(method_exists ( $connector , 'beforeTransaction' ))
  53. $connector::beforeTransaction($this->connections[$baseUid]);
  54. } catch (Exception $e) {
  55. echo 'Connection à la base impossible : ', $e->getMessage();
  56. die();
  57. }
  58. }
  59. }