1: <?php
2:
3: namespace PHPixie;
4:
5: class Database
6: {
7: protected $config;
8: protected $values;
9: protected $sql;
10: protected $document;
11: protected $driverClasses = array(
12: 'pdo' => '\PHPixie\Database\Driver\PDO',
13: 'mongo' => '\PHPixie\Database\Driver\Mongo',
14: );
15: protected $drivers = array();
16: protected $connections = array();
17:
18: public function __construct($config)
19: {
20: $this->config = $config;
21: }
22:
23: public function get($connectionName = 'default')
24: {
25: if (!isset($this->connections[$connectionName])) {
26: $config = $this->config->slice($connectionName);
27: $driverName = $this->configDriverName($config);
28: $driver = $this->driver($driverName);
29: $this->connections[$connectionName] = $driver->buildConnection($connectionName, $config);
30: }
31:
32: return $this->connections[$connectionName];
33: }
34:
35: public function connectionDriverName($connectionName)
36: {
37: $config = $this->config->slice($connectionName);
38: return $this->configDriverName($config);
39: }
40:
41: public function driver($name)
42: {
43: if (!isset($this->drivers[$name])) {
44: $this->drivers[$name] = $this->buildDriver($name);
45: }
46: return $this->drivers[$name];
47: }
48:
49: public function buildDriver($name)
50: {
51: $class = $this->driverClasses[$name];
52: return new $class($this);
53: }
54:
55: public function values()
56: {
57: if ($this->values === null)
58: $this->values = $this->buildValues();
59:
60: return $this->values;
61: }
62:
63: public function sqlExpression($sql = '', $params = array())
64: {
65: return $this->sql()->expression($sql, $params);
66: }
67:
68: public function sql()
69: {
70: if ($this->sql === null)
71: $this->sql = $this->buildSql();
72:
73: return $this->sql;
74: }
75:
76: protected function configDriverName($config)
77: {
78: $driverName = $config->get('driver');
79: if(!array_key_exists($driverName, $this->driverClasses)) {
80: throw new \PHPixie\Database\Exception\Driver("Driver '$driverName' does not exist");
81: }
82:
83: return $driverName;
84: }
85:
86: protected function buildValues()
87: {
88: return new \PHPixie\Database\Values();
89: }
90:
91: protected function buildSql()
92: {
93: return new \PHPixie\Database\Type\SQL();
94: }
95:
96: }
97: