1: <?php
2:
3: namespace PHPixie\Database\Driver\Mongo;
4:
5: class Connection extends \PHPixie\Database\Connection
6: {
7: protected $client;
8: protected $databaseName;
9: protected $database;
10: protected $lastInsertId;
11:
12: public function connect()
13: {
14: $config = $this->config;
15:
16: $options = $config->get('connectionOptions', array());
17: if (!is_array($options))
18: throw new \PHPixie\Database\Exception("Mongo 'connectionOptions' configuration parameter must be an array");
19:
20: $options['username'] = $config->get('user', '');
21: $options['password'] = $config->get('password', '');
22:
23: $this->databaseName = $config->get('database');
24: $options['db'] = $this->databaseName;
25:
26: $this->client = $this->buildMongoClient($config->get('connection'), $options);
27: }
28:
29: public function disconnect()
30: {
31: $this->client->close();
32: $this->client = null;
33: }
34:
35: public function selectSingleQuery()
36: {
37: return $this->driver->query('selectSingle', $this->name);
38: }
39:
40: public function insertId()
41: {
42: return $this->lastInsertId;
43: }
44:
45: public function run($runner)
46: {
47: $result = $runner->run($this);
48: if ($result instanceof \MongoCursor) {
49: return $this->driver->result($result);
50: }
51: return $result;
52: }
53:
54: public function setInsertId($id)
55: {
56: $this->lastInsertId = $id;
57: }
58:
59: protected function buildMongoClient($connection, $options)
60: {
61: return new \MongoClient($connection, $options);
62: }
63:
64: public function client()
65: {
66: return $this->client;
67: }
68:
69: public function database()
70: {
71: if ($this->database === null)
72: $this->database = $this->client()->{$this->databaseName};
73:
74: return $this->database;
75: }
76: }
77: