1
|
|
|
<?php |
2
|
|
|
namespace Wandu\Database; |
3
|
|
|
|
4
|
|
|
class DatabaseManager |
5
|
|
|
{ |
6
|
|
|
/** @var \Wandu\Database\Connector[] */ |
7
|
|
|
protected $connectors = []; |
8
|
|
|
|
9
|
|
|
/** @var \Wandu\Database\Contracts\Connection[] */ |
10
|
|
|
protected $connections = []; |
11
|
|
|
|
12
|
|
|
/** @var \Wandu\Database\Repository[] */ |
13
|
|
|
protected $repositories = []; |
14
|
|
|
|
15
|
19 |
|
public function __construct(Configuration $config) |
16
|
|
|
{ |
17
|
19 |
|
$this->config = $config; |
|
|
|
|
18
|
19 |
|
} |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @param array|\Wandu\Database\Connector $connector |
22
|
|
|
* @param string $name |
23
|
|
|
* @return \Wandu\Database\Contracts\Connection |
24
|
|
|
*/ |
25
|
19 |
|
public function connect($connector, $name = 'default') |
26
|
|
|
{ |
27
|
19 |
|
if (is_array($connector)) { |
28
|
19 |
|
$connector = new Connector($connector); |
29
|
|
|
} |
30
|
19 |
|
$this->connectors[$name] = $connector; |
31
|
19 |
|
$connection = $connector->connect(); |
32
|
18 |
|
if ($emitter = $this->config->getEmitter()) { |
33
|
17 |
|
$connection->setEventEmitter($emitter); |
34
|
|
|
} |
35
|
18 |
|
return $this->connections[$name] = $connection; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @param string $name |
40
|
|
|
* @return \Wandu\Database\Contracts\Connection |
41
|
|
|
*/ |
42
|
|
|
public function connection($name = 'default') |
43
|
|
|
{ |
44
|
|
|
return isset($this->connections[$name]) ? $this->connections[$name] : null; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @param string $class |
49
|
|
|
* @return \Wandu\Database\Repository |
50
|
|
|
*/ |
51
|
15 |
|
public function repository(string $class): Repository |
52
|
|
|
{ |
53
|
15 |
|
if (!isset($this->repositories[$class])) { |
54
|
|
|
|
55
|
15 |
|
$meta = $this->config->getMetadataReader()->getMetadata($class); |
56
|
15 |
|
$connection = $meta->getConnection(); |
57
|
15 |
|
$prefix = $this->connectors[$connection]->getPrefix(); |
58
|
|
|
|
59
|
15 |
|
$this->repositories[$class] = new Repository( |
60
|
|
|
$this, |
61
|
15 |
|
$this->connections[$connection], |
62
|
15 |
|
new QueryBuilder($prefix . $meta->getTable()), |
63
|
|
|
$meta, |
64
|
15 |
|
$this->config |
65
|
|
|
); |
66
|
|
|
} |
67
|
15 |
|
return $this->repositories[$class]; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: