Connection.php 8.62 KB
Newer Older
1 2 3 4 5 6 7
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

8
namespace yii\mongodb;
9 10 11 12 13 14

use yii\base\Component;
use yii\base\InvalidConfigException;
use Yii;

/**
15 16 17 18 19 20 21 22 23 24 25
 * Connection represents a connection to a MongoDb server.
 *
 * Connection works together with [[Database]] and [[Collection]] to provide data access
 * to the Mongo database. They are wrappers of the [[MongoDB PHP extension]](http://us1.php.net/manual/en/book.mongo.php).
 *
 * To establish a DB connection, set [[dsn]] and then call [[open()]] to be true.
 *
 * The following example shows how to create a Connection instance and establish
 * the DB connection:
 *
 * ~~~
26
 * $connection = new \yii\mongodb\Connection([
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
 *     'dsn' => $dsn,
 * ]);
 * $connection->open();
 * ~~~
 *
 * After the Mongo connection is established, one can access Mongo databases and collections:
 *
 * ~~~
 * $database = $connection->getDatabase('my_mongo_db');
 * $collection = $database->getCollection('customer');
 * $collection->insert(['name' => 'John Smith', 'status' => 1]);
 * ~~~
 *
 * You can work with several different databases at the same server using this class.
 * However, while it is unlikely your application will actually need it, the Connection class
 * provides ability to use [[defaultDatabaseName]] as well as a shortcut method [[getCollection()]]
 * to retrieve a particular collection instance:
 *
 * ~~~
 * // get collection 'customer' from default database:
 * $collection = $connection->getCollection('customer');
 * // get collection 'customer' from database 'mydatabase':
 * $collection = $connection->getCollection(['mydatabase', 'customer']);
 * ~~~
 *
 * Connection is often used as an application component and configured in the application
 * configuration like the following:
 *
 * ~~~
 * [
 *	 'components' => [
58 59
 *		 'mongodb' => [
 *			 'class' => '\yii\mongodb\Connection',
60 61 62 63 64
 *			 'dsn' => 'mongodb://developer:password@localhost:27017/mydatabase',
 *		 ],
 *	 ],
 * ]
 * ~~~
65
 *
Qiang Xue committed
66 67
 * @property Database $database Database instance. This property is read-only.
 * @property file\Collection $fileCollection Mongo GridFS collection instance. This property is read-only.
Paul Klimov committed
68 69
 * @property boolean $isActive Whether the Mongo connection is established. This property is read-only.
 *
70 71 72 73 74
 * @author Paul Klimov <klimov.paul@gmail.com>
 * @since 2.0
 */
class Connection extends Component
{
75 76 77 78 79
	/**
	 * @event Event an event that is triggered after a DB connection is established
	 */
	const EVENT_AFTER_OPEN = 'afterOpen';

80
	/**
81 82 83 84 85 86
	 * @var string host:port
	 *
	 * Correct syntax is:
	 * mongodb://[username:password@]host1[:port1][,host2[:port2:],...][/dbname]
	 * For example:
	 * mongodb://localhost:27017
87 88
	 * mongodb://developer:password@localhost:27017
	 * mongodb://developer:password@localhost:27017/mydatabase
89
	 */
90
	public $dsn;
91 92 93
	/**
	 * @var array connection options.
	 * for example:
94
	 *
95 96 97 98 99 100
	 * ~~~
	 * [
	 *     'socketTimeoutMS' => 1000, // how long a send or receive on a socket can take before timing out
	 *     'journal' => true // block write operations until the journal be flushed the to disk
	 * ]
	 * ~~~
101 102
	 *
	 * @see http://www.php.net/manual/en/mongoclient.construct.php
103 104 105
	 */
	public $options = [];
	/**
106
	 * @var string name of the Mongo database to use by default.
107 108
	 * If this field left blank, connection instance will attempt to determine it from
	 * [[options]] and [[dsn]] automatically, if needed.
109
	 */
110 111
	public $defaultDatabaseName;
	/**
112
	 * @var \MongoClient Mongo client instance.
113 114 115 116 117 118 119 120 121 122
	 */
	public $mongoClient;
	/**
	 * @var Database[] list of Mongo databases
	 */
	private $_databases = [];

	/**
	 * Returns the Mongo collection with the given name.
	 * @param string|null $name collection name, if null default one will be used.
123
	 * @param boolean $refresh whether to reestablish the database connection even if it is found in the cache.
124 125 126 127 128 129 130 131 132 133 134 135 136
	 * @return Database database instance.
	 */
	public function getDatabase($name = null, $refresh = false)
	{
		if ($name === null) {
			$name = $this->fetchDefaultDatabaseName();
		}
		if ($refresh || !array_key_exists($name, $this->_databases)) {
			$this->_databases[$name] = $this->selectDatabase($name);
		}
		return $this->_databases[$name];
	}

137
	/**
138 139 140 141
	 * Returns [[defaultDatabaseName]] value, if it is not set,
	 * attempts to determine it from [[dsn]] value.
	 * @return string default database name
	 * @throws \yii\base\InvalidConfigException if unable to determine default database name.
142
	 */
143 144 145
	protected function fetchDefaultDatabaseName()
	{
		if ($this->defaultDatabaseName === null) {
146 147 148
			if (isset($this->options['db'])) {
				$this->defaultDatabaseName = $this->options['db'];
			} elseif (preg_match('/^mongodb:\\/\\/.+\\/(.+)$/s', $this->dsn, $matches)) {
149 150 151 152 153 154 155 156
				$this->defaultDatabaseName = $matches[1];
			} else {
				throw new InvalidConfigException("Unable to determine default database name from dsn.");
			}
		}
		return $this->defaultDatabaseName;
	}

157
	/**
158 159 160
	 * Selects the database with given name.
	 * @param string $name database name.
	 * @return Database database instance.
161
	 */
162 163 164 165
	protected function selectDatabase($name)
	{
		$this->open();
		return Yii::createObject([
166
			'class' => 'yii\mongodb\Database',
167 168 169
			'mongoDb' => $this->mongoClient->selectDB($name)
		]);
	}
170 171 172

	/**
	 * Returns the Mongo collection with the given name.
173
	 * @param string|array $name collection name. If string considered as the name of the collection
174 175
	 * inside the default database. If array - first element considered as the name of the database,
	 * second - as name of collection inside that database
176
	 * @param boolean $refresh whether to reload the collection instance even if it is found in the cache.
177
	 * @return Collection Mongo collection instance.
178 179 180
	 */
	public function getCollection($name, $refresh = false)
	{
181 182 183 184 185
		if (is_array($name)) {
			list ($dbName, $collectionName) = $name;
			return $this->getDatabase($dbName)->getCollection($collectionName, $refresh);
		} else {
			return $this->getDatabase()->getCollection($name, $refresh);
186 187
		}
	}
188

189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
	/**
	 * Returns the Mongo GridFS collection.
	 * @param string|array $prefix collection prefix. If string considered as the prefix of the GridFS
	 * collection inside the default database. If array - first element considered as the name of the database,
	 * second - as prefix of the GridFS collection inside that database, if no second element present
	 * default "fs" prefix will be used.
	 * @param boolean $refresh whether to reload the collection instance even if it is found in the cache.
	 * @return file\Collection Mongo GridFS collection instance.
	 */
	public function getFileCollection($prefix = 'fs', $refresh = false)
	{
		if (is_array($prefix)) {
			list ($dbName, $collectionPrefix) = $prefix;
			if (!isset($collectionPrefix)) {
				$collectionPrefix = 'fs';
			}
			return $this->getDatabase($dbName)->getFileCollection($collectionPrefix, $refresh);
		} else {
			return $this->getDatabase()->getFileCollection($prefix, $refresh);
		}
	}

Paul Klimov committed
211 212 213 214 215 216
	/**
	 * Returns a value indicating whether the Mongo connection is established.
	 * @return boolean whether the Mongo connection is established
	 */
	public function getIsActive()
	{
217
		return is_object($this->mongoClient) && $this->mongoClient->connected;
Paul Klimov committed
218 219
	}

220 221 222 223 224 225 226
	/**
	 * Establishes a Mongo connection.
	 * It does nothing if a Mongo connection has already been established.
	 * @throws Exception if connection fails
	 */
	public function open()
	{
227
		if ($this->mongoClient === null) {
228
			if (empty($this->dsn)) {
229
				throw new InvalidConfigException($this->className() . '::dsn cannot be empty.');
230
			}
231
			$token = 'Opening MongoDB connection: ' . $this->dsn;
232 233 234 235 236
			try {
				Yii::trace($token, __METHOD__);
				Yii::beginProfile($token, __METHOD__);
				$options = $this->options;
				$options['connect'] = true;
237 238 239 240
				if ($this->defaultDatabaseName !== null) {
					$options['db'] = $this->defaultDatabaseName;
				}
				$this->mongoClient = new \MongoClient($this->dsn, $options);
241
				$this->initConnection();
242 243 244
				Yii::endProfile($token, __METHOD__);
			} catch (\Exception $e) {
				Yii::endProfile($token, __METHOD__);
Paul Klimov committed
245
				throw new Exception($e->getMessage(), (int)$e->getCode(), $e);
246 247 248 249 250 251 252 253 254 255
			}
		}
	}

	/**
	 * Closes the currently active DB connection.
	 * It does nothing if the connection is already closed.
	 */
	public function close()
	{
256
		if ($this->mongoClient !== null) {
257
			Yii::trace('Closing MongoDB connection: ' . $this->dsn, __METHOD__);
258 259
			$this->mongoClient = null;
			$this->_databases = [];
260 261
		}
	}
262 263 264 265 266 267 268 269 270 271

	/**
	 * Initializes the DB connection.
	 * This method is invoked right after the DB connection is established.
	 * The default implementation triggers an [[EVENT_AFTER_OPEN]] event.
	 */
	protected function initConnection()
	{
		$this->trigger(self::EVENT_AFTER_OPEN);
	}
AlexGx committed
272
}