1 | <?php |
||
17 | class DBConfig extends PDO |
||
18 | { |
||
19 | protected $driver; |
||
20 | protected $host; |
||
21 | protected $dbname; |
||
22 | protected $port; |
||
23 | protected $user; |
||
24 | protected $password; |
||
25 | protected $sqlitePath; |
||
26 | |||
27 | /** |
||
28 | * Define the database connection |
||
29 | */ |
||
30 | public function __construct() |
||
31 | { |
||
32 | $this->loadEnv(); |
||
33 | $this->driver = getenv('DATABASE_DRIVER'); |
||
34 | $this->host = getenv('DATABASE_HOST'); |
||
35 | $this->dbname = getenv('DATABASE_NAME'); |
||
36 | $this->port = getenv('DATABASE_PORT'); |
||
37 | $this->user = getenv('DATABASE_USER'); |
||
38 | $this->password = getenv('DATABASE_PASSWORD'); |
||
39 | $this->sqlitePath = getenv('SQLITE_PATH'); |
||
40 | try |
||
41 | { |
||
42 | if ($this->driver === 'pgsql' || $this->driver === 'postgres') |
||
43 | { |
||
44 | parent::__construct($this->pgsqlConnectionString()); |
||
45 | } |
||
46 | elseif ($this->driver === 'mysql') |
||
47 | { |
||
48 | parent::__construct($this->mysqlConnectionString(), $this->user, $this->password); |
||
49 | } |
||
50 | elseif($this->driver === 'sqlite') |
||
51 | { |
||
52 | parent::__construct($this->sqlitConnectionString()); |
||
53 | } |
||
54 | } catch (PDOException $e) { |
||
55 | $e->getMessage(); |
||
56 | } |
||
57 | } |
||
58 | |||
59 | /** |
||
60 | * pgsqlConnectionString Postgres connection string |
||
61 | * |
||
62 | * @return string |
||
63 | */ |
||
64 | protected function pgsqlConnectionString() |
||
68 | |||
69 | /** |
||
70 | * mysqlConnectionString Mysql connection string |
||
71 | * |
||
72 | * @return string |
||
73 | */ |
||
74 | protected function mysqlConnectionString() |
||
78 | |||
79 | /** |
||
80 | * sqliteConnectionString Sqlite connection string |
||
81 | * |
||
82 | * @return string |
||
83 | */ |
||
84 | protected function sqlitConnectionString() |
||
88 | |||
89 | /** |
||
90 | * Load Dotenv to grant getenv() access to environment variables in .env file |
||
91 | */ |
||
92 | protected function loadEnv() |
||
100 | } |
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: