|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* This class is involve in connection to the database. |
|
5
|
|
|
* |
|
6
|
|
|
* @author Raimi Ademola <[email protected]> |
|
7
|
|
|
* @copyright: 2016 Andela |
|
8
|
|
|
*/ |
|
9
|
|
|
namespace Demo; |
|
10
|
|
|
|
|
11
|
|
|
use Dotenv\Dotenv; |
|
12
|
|
|
use PDO; |
|
13
|
|
|
|
|
14
|
|
|
class DataBaseConnection extends PDO |
|
15
|
|
|
{ |
|
16
|
|
|
private $servername; |
|
17
|
|
|
private $username; |
|
18
|
|
|
private $password; |
|
19
|
|
|
private $driver; |
|
20
|
|
|
private $dbname; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* This is a constructor; a default method that will be called automatically during class instantiation. |
|
24
|
|
|
*/ |
|
25
|
|
|
public function __construct() |
|
26
|
|
|
{ |
|
27
|
|
|
$this->loadEnv(); |
|
28
|
|
|
|
|
29
|
|
|
$this->servername = getenv('DB_HOST'); |
|
30
|
|
|
$this->username = getenv('DB_USERNAME'); |
|
31
|
|
|
$this->password = getenv('DB_PASSWORD'); |
|
32
|
|
|
$this->driver = getenv('DB_DRIVER'); |
|
33
|
|
|
$this->dbname = getenv('DB_NAME'); |
|
34
|
|
|
|
|
35
|
|
|
$options = [ |
|
36
|
|
|
PDO::ATTR_PERSISTENT => true, |
|
37
|
|
|
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, |
|
38
|
|
|
]; |
|
39
|
|
|
|
|
40
|
|
|
parent::__construct($this->getDataBaseDriver(), $this->username, $this->password, $options); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* This method determines the driver to be used for appropriate database server. |
|
45
|
|
|
* |
|
46
|
|
|
* |
|
47
|
|
|
* @return string dsn |
|
48
|
|
|
*/ |
|
49
|
|
|
public function getDataBaseDriver() |
|
50
|
|
|
{ |
|
51
|
|
|
if ($this->driver === 'mysql') { |
|
52
|
|
|
$dns = 'mysql:host='.$this->servername.';dbname='.$this->dbname; |
|
53
|
|
|
|
|
54
|
|
|
return $dns; |
|
55
|
|
|
} elseif ($this->driver === 'sqlite') { |
|
56
|
|
|
$dns = 'sqlite:host='.$this->servername.';dbname='.$this->dbname; |
|
57
|
|
|
|
|
58
|
|
|
return $dns; |
|
59
|
|
|
} elseif ($this->driver === 'pgsqlsql') { |
|
60
|
|
|
$dns = 'pgsqlsql:host='.$this->servername.';dbname='.$this->dbname; |
|
61
|
|
|
|
|
62
|
|
|
return $dns; |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
/** |
|
67
|
|
|
* Load Dotenv to grant getenv() access to environment variables in .env file. |
|
68
|
|
|
*/ |
|
69
|
|
|
private function loadEnv() |
|
70
|
|
|
{ |
|
71
|
|
|
$dotenv = new Dotenv(__DIR__.'/../../'); |
|
72
|
|
|
$dotenv->load(); |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|