|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Simply\Database\Connection\Provider; |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* A generic lazy loading connector that can take any kind of PDO data source name. |
|
7
|
|
|
* @author Riikka Kalliomäki <[email protected]> |
|
8
|
|
|
* @copyright Copyright (c) 2018 Riikka Kalliomäki |
|
9
|
|
|
* @license http://opensource.org/licenses/mit-license.php MIT License |
|
10
|
|
|
*/ |
|
11
|
|
|
class GenericConnectionProvider implements ConnectionProvider |
|
12
|
|
|
{ |
|
13
|
|
|
/** @var string The data source name for the PDO connection */ |
|
14
|
|
|
private $dsn; |
|
15
|
|
|
|
|
16
|
|
|
/** @var string The username for the PDO connection */ |
|
17
|
|
|
private $username; |
|
18
|
|
|
|
|
19
|
|
|
/** @var string The password for the PDO connection */ |
|
20
|
|
|
private $password; |
|
21
|
|
|
|
|
22
|
|
|
/** @var array Initial PDO options provided when initializing the connection */ |
|
23
|
|
|
private $options; |
|
24
|
|
|
|
|
25
|
|
|
/** @var \PDO The active PDO connection */ |
|
26
|
|
|
private $pdo; |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* GenericConnectionProvider constructor. |
|
30
|
|
|
* @param string $dsn The data source name for the PDO connection |
|
31
|
|
|
* @param string $username The username for the PDO connection |
|
32
|
|
|
* @param string $password The password for the PDO connection |
|
33
|
|
|
* @param array $options Initial PDO options provided when initializing the connection |
|
34
|
|
|
*/ |
|
35
|
25 |
|
public function __construct(string $dsn, string $username, string $password, array $options) |
|
36
|
|
|
{ |
|
37
|
25 |
|
$this->dsn = $dsn; |
|
38
|
25 |
|
$this->username = $username; |
|
39
|
25 |
|
$this->password = $password; |
|
40
|
25 |
|
$this->options = $options; |
|
41
|
25 |
|
} |
|
42
|
|
|
|
|
43
|
25 |
|
public function getConnection(): \PDO |
|
44
|
|
|
{ |
|
45
|
25 |
|
if (!isset($this->pdo)) { |
|
46
|
25 |
|
$this->pdo = $this->initializeConnection(); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
25 |
|
return $this->pdo; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* Initializes the PDO connection when first requested. |
|
54
|
|
|
* @return \PDO The initialized PDO connection |
|
55
|
|
|
*/ |
|
56
|
25 |
|
protected function initializeConnection(): \PDO |
|
57
|
|
|
{ |
|
58
|
25 |
|
return new \PDO($this->dsn, $this->username, $this->password, $this->options); |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
|