|
1
|
|
|
<?php |
|
2
|
|
|
namespace Wandu\Database; |
|
3
|
|
|
|
|
4
|
|
|
use ArrayAccess; |
|
5
|
|
|
use Wandu\Database\Connector\MysqlConnector; |
|
6
|
|
|
use Wandu\Database\Contracts\ConnectionInterface; |
|
7
|
|
|
use Wandu\Database\Contracts\ConnectorInterface; |
|
8
|
|
|
use Wandu\Database\Exception\DriverNotFoundException; |
|
9
|
|
|
|
|
10
|
|
|
class Manager |
|
11
|
|
|
{ |
|
12
|
|
|
/** @var \ArrayAccess */ |
|
13
|
|
|
protected $container; |
|
14
|
|
|
|
|
15
|
|
|
/** @var \Wandu\Database\Contracts\ConnectionInterface[] */ |
|
16
|
|
|
protected $connections = []; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* @param \ArrayAccess $container |
|
20
|
|
|
*/ |
|
21
|
2 |
|
public function __construct(ArrayAccess $container = null) |
|
22
|
|
|
{ |
|
23
|
2 |
|
$this->container = $container; |
|
24
|
2 |
|
} |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* @param array|\Wandu\Database\Contracts\ConnectorInterface $information |
|
28
|
|
|
* @param string $name |
|
29
|
|
|
* @return \Wandu\Database\Contracts\ConnectionInterface |
|
30
|
|
|
*/ |
|
31
|
2 |
|
public function connect($information, $name = 'default') |
|
32
|
|
|
{ |
|
33
|
2 |
|
if (!$information instanceof ConnectorInterface) { |
|
34
|
2 |
|
$information = $this->getConnectorFromConfig($information); |
|
35
|
|
|
} |
|
36
|
1 |
|
return $this->setConnection($information->connect($this->container), $name); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* @param \Wandu\Database\Contracts\ConnectionInterface $connection |
|
41
|
|
|
* @param string $name |
|
42
|
|
|
* @return \Wandu\Database\Contracts\ConnectionInterface |
|
43
|
|
|
*/ |
|
44
|
1 |
|
public function setConnection(ConnectionInterface $connection, $name = 'default') |
|
45
|
|
|
{ |
|
46
|
1 |
|
return $this->connections[$name] = $connection; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* @param string $name |
|
51
|
|
|
* @return \Wandu\Database\Contracts\ConnectionInterface |
|
52
|
|
|
*/ |
|
53
|
|
|
public function getConnection($name = 'defeault') |
|
54
|
|
|
{ |
|
55
|
|
|
return isset($this->connections[$name]) ? $this->connections[$name] : null; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* @param array $config |
|
60
|
|
|
* @return \Wandu\Database\Contracts\ConnectorInterface |
|
61
|
|
|
*/ |
|
62
|
2 |
|
private function getConnectorFromConfig(array $config) |
|
63
|
|
|
{ |
|
64
|
2 |
|
if (!isset($config['driver'])) { |
|
65
|
1 |
|
throw new DriverNotFoundException(); |
|
66
|
|
|
} |
|
67
|
2 |
|
switch ($config['driver']) { |
|
68
|
2 |
|
case 'mysql': |
|
69
|
1 |
|
return new MysqlConnector($config); |
|
70
|
|
|
} |
|
71
|
1 |
|
throw new DriverNotFoundException($config['driver']); |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|