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