1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ez\DbLinker\Driver; |
4
|
|
|
|
5
|
|
|
use Ez\DbLinker\Driver\Connection\MasterSlavesConnection; |
6
|
|
|
use Cache\Adapter\Apcu\ApcuCachePool; |
7
|
|
|
use Ez\DbLinker\Cache; |
8
|
|
|
|
9
|
|
|
trait MasterSlavesDriver |
10
|
|
|
{ |
11
|
|
|
private $cache; |
12
|
|
|
private $cacheDefaultTtl = 60; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Attempts to create a connection with the database. |
16
|
|
|
* |
17
|
|
|
* @param array $params All connection parameters passed by the user. |
18
|
|
|
* @param string|null $username The username to use when connecting. |
19
|
|
|
* @param string|null $password The password to use when connecting. |
20
|
|
|
* @param array $driverOptions The driver options to use when connecting. |
21
|
|
|
* |
22
|
|
|
* @return \Doctrine\DBAL\Driver\Connection The database connection. |
23
|
|
|
*/ |
24
|
|
|
public function connect(array $params, $username = null, $password = null, array $driverOptions = []) { |
25
|
|
|
$cacheDriver = array_key_exists("config_cache", $driverOptions) ? $driverOptions["config_cache"] : null; |
26
|
|
|
|
27
|
|
|
$configParams = array_intersect_key($params, array_flip(["master", "slaves"])); |
28
|
|
|
$key = "dblinker.master-slave-config.".hash("sha256", serialize($configParams)); |
29
|
|
|
|
30
|
|
|
$config = null; |
31
|
|
|
|
32
|
|
|
// default cache, disable it with $cache = false |
33
|
|
|
$cache = new Cache($cacheDriver); |
34
|
|
|
|
35
|
|
|
if ($cache->hasCache()) { |
36
|
|
|
$config = $cache->getCacheItem($key); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
if ($config === null) { |
40
|
|
|
$config = $this->config($configParams, $driverOptions); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
if ($cache->hasCache()) { |
44
|
|
|
$cache->setCacheItem($key, $config, 60); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
return new MasterSlavesConnection($config["master"], $config["slaves"], $cache); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
private function config(array $params, array $driverOptions) |
51
|
|
|
{ |
52
|
|
|
$driverKey = array_key_exists('driverClass', $params['master']) ? 'driverClass' : 'driver'; |
53
|
|
|
|
54
|
|
|
$driverValue = $params['master'][$driverKey]; |
55
|
|
|
|
56
|
|
|
$slaves = []; |
57
|
|
|
foreach ($params['slaves'] as $slaveParams) { |
58
|
|
|
$slaveParams[$driverKey] = $driverValue; |
59
|
|
|
$slaves[] = $slaveParams; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
$config = [ |
63
|
|
|
"master" => $params["master"], |
64
|
|
|
"slaves" => $slaves, |
65
|
|
|
]; |
66
|
|
|
|
67
|
|
|
if (!array_key_exists("config_transform", $driverOptions)) { |
68
|
|
|
return $config; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
assert(is_callable($driverOptions["config_transform"])); |
72
|
|
|
return $driverOptions["config_transform"]($config); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
} |
76
|
|
|
|