Database.class.php 1.8 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 copyright
  11. */
  12. class Database
  13. {
  14. public $connection = null;
  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()
  28. {
  29. if (self::$instance === null) {
  30. self::$instance = new self();
  31. }
  32. return self::$instance->connection;
  33. }
  34. public static function version(){
  35. try {
  36. $db = new self();
  37. $db->connect();
  38. return $db->connection->getAttribute(PDO::ATTR_SERVER_VERSION);
  39. } catch (Exception $e) {
  40. return 'Connection à la base impossible : '. $e->getMessage();
  41. }
  42. }
  43. public function connect()
  44. {
  45. try {
  46. $base = BASE_SGBD;
  47. require_once(__ROOT__.'connector/'.$base.'.class.php');
  48. $connectionString = str_replace(
  49. array('{{ROOT}}','{{BASE_HOST}}','{{BASE_NAME}}','{{BASE_LOGIN}}','{{BASE_PASSWORD}}'),
  50. array(__ROOT__,BASE_HOST,BASE_NAME,BASE_LOGIN,BASE_PASSWORD),
  51. $base::connection);
  52. $this->connection = new PDO($connectionString, BASE_LOGIN, BASE_PASSWORD,array(
  53. PDO::ATTR_PERSISTENT => true
  54. ));
  55. $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  56. if(method_exists ( $base , 'beforeTransaction' ))
  57. $base::beforeTransaction($this->connection);
  58. } catch (Exception $e) {
  59. echo 'Connection à la base impossible : ', $e->getMessage();
  60. die();
  61. }
  62. }
  63. }