Class yii\mongodb\Connection
Inheritance | yii\mongodb\Connection » yii\base\Component |
---|---|
Available since extension's version | 2.0 |
Source Code | https://github.com/yiisoft/yii2-mongodb/blob/master/src/Connection.php |
Connection represents a connection to a MongoDb server.
Connection works together with yii\mongodb\Database and yii\mongodb\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:
$connection = new \yii\mongodb\Connection([
'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' => [
'mongodb' => [
'class' => '\yii\mongodb\Connection',
'dsn' => 'mongodb://developer:password@localhost:27017/mydatabase',
],
],
]
Public Properties
Property | Type | Description | Defined By |
---|---|---|---|
$database | yii\mongodb\Database | Database instance. | yii\mongodb\Connection |
$defaultDatabaseName | string | Default database name. | yii\mongodb\Connection |
$driverOptions | array | Options for the MongoDB driver. | yii\mongodb\Connection |
$dsn | string | Host:port Correct syntax is: mongodb://[username:password@]host1[:port1][,host2[:port2:],...][/dbname] For example: mongodb://localhost:27017 mongodb://developer:password@localhost:27017 mongodb://developer:password@localhost:27017/mydatabase | yii\mongodb\Connection |
$enableLogging | boolean | Whether to log command and query executions. | yii\mongodb\Connection |
$enableProfiling | boolean | Whether to enable profiling the commands and queries being executed. | yii\mongodb\Connection |
$fileCollection | yii\mongodb\file\Collection | Mongo GridFS collection instance. | yii\mongodb\Connection |
$fileStreamProtocol | string | Name of the protocol, which should be used for the GridFS stream wrapper. | yii\mongodb\Connection |
$fileStreamWrapperClass | string | Name of the class, which should serve as a stream wrapper for $fileStreamProtocol protocol. | yii\mongodb\Connection |
$globalExecOptions | array | Default options for executeCommand , executeBulkWrite and executeQuery method of MongoDB\Driver\Manager in Command class. |
yii\mongodb\Connection |
$isActive | boolean | Whether the Mongo connection is established. | yii\mongodb\Connection |
$logBuilder | yii\mongodb\LogBuilder | The log builder for this connection. | yii\mongodb\Connection |
$manager | \MongoDB\Driver\Manager | MongoDB driver manager. | yii\mongodb\Connection |
$options | array | Connection options. | yii\mongodb\Connection |
$queryBuilder | yii\mongodb\QueryBuilder | The query builder for the this MongoDB connection. | yii\mongodb\Connection |
$session | yii\mongodb\ClientSession|null | New instance of ClientSession to replace return $this. | yii\mongodb\Connection |
$typeMap | array | Type map to use for BSON unserialization. | yii\mongodb\Connection |
Public Methods
Method | Description | Defined By |
---|---|---|
close() | Closes the currently active DB connection. | yii\mongodb\Connection |
commitTransaction() | Commits transaction in current session | yii\mongodb\Connection |
createCommand() | Creates MongoDB command. | yii\mongodb\Connection |
execOptions() | Recursive replacement on $this->globalExecOptions with new options. {@see $this->globalExecOptions} | yii\mongodb\Connection |
getCollection() | Returns the MongoDB collection with the given name. | yii\mongodb\Connection |
getDatabase() | Returns the MongoDB database with the given name. | yii\mongodb\Connection |
getDefaultDatabaseName() | Returns default database name, if it is not set, attempts to determine it from $dsn value. | yii\mongodb\Connection |
getFileCollection() | Returns the MongoDB GridFS collection. | yii\mongodb\Connection |
getInSession() | Checks whether the current connection is in session. | yii\mongodb\Connection |
getInTransaction() | Checks that the current connection is in session and transaction return bool | yii\mongodb\Connection |
getIsActive() | Returns a value indicating whether the Mongo connection is established. | yii\mongodb\Connection |
getLogBuilder() | Returns log builder for this connection. | yii\mongodb\Connection |
getQueryBuilder() | Returns the query builder for the this MongoDB connection. | yii\mongodb\Connection |
getSession() | Returns current session return ClientSession|null | yii\mongodb\Connection |
newSession() | Only starts the new session for current connection but this session does not set for current connection. | yii\mongodb\Connection |
noTransaction() | Runs your mongodb command out of session and transaction. | yii\mongodb\Connection |
open() | Establishes a Mongo connection. | yii\mongodb\Connection |
registerFileStreamWrapper() | Registers GridFS stream wrapper for the $fileStreamProtocol protocol. | yii\mongodb\Connection |
rollBackTransaction() | Rollbacks transaction in current session | yii\mongodb\Connection |
setDefaultDatabaseName() | Sets default database name. | yii\mongodb\Connection |
setLogBuilder() | Sets log builder used for this connection. | yii\mongodb\Connection |
setQueryBuilder() | Sets the query builder for the this MongoDB connection. | yii\mongodb\Connection |
setSession() | Changes the current session of connection to execute commands (or drop session) | yii\mongodb\Connection |
startSession() | Ends the previous session and starts the new session. | yii\mongodb\Connection |
startSessionOnce() | Starts a new session if the session has not started, otherwise returns previous session. | yii\mongodb\Connection |
startTransaction() | Starts a transaction with three steps : - starts new session if has not started - starts the transaction in new session - sets new session to current connection | yii\mongodb\Connection |
startTransactionOnce() | Starts a transaction in current session if the previous transaction was not started in current session. | yii\mongodb\Connection |
transaction() | Starts and commits a transaction in easy mode. | yii\mongodb\Connection |
transactionOnce() | Starts and commits transaction in easy mode if the previous transaction was not executed, otherwise only runs your actions in previous transaction. | yii\mongodb\Connection |
transactionReady() | Throws custom error if transaction is not ready in connection | yii\mongodb\Connection |
Protected Methods
Method | Description | Defined By |
---|---|---|
initConnection() | Initializes the DB connection. | yii\mongodb\Connection |
selectDatabase() | Selects the database with given name. | yii\mongodb\Connection |
Events
Event | Type | Description | Defined By |
---|---|---|---|
EVENT_AFTER_OPEN | yii\mongodb\Event | An event that is triggered after a DB connection is established | yii\mongodb\Connection |
EVENT_COMMIT_TRANSACTION | yii\base\Event | An event that is triggered right after a transaction is committed | yii\mongodb\Connection |
EVENT_END_SESSION | yii\base\Event | An event that is triggered right after a mongo client session is ended | yii\mongodb\Connection |
EVENT_ROLLBACK_TRANSACTION | yii\base\Event | An event that is triggered right after a transaction is rolled back | yii\mongodb\Connection |
EVENT_START_SESSION | yii\base\Event | An event that is triggered right before a mongo client session is started | yii\mongodb\Connection |
EVENT_START_TRANSACTION | yii\base\Event | An event that is triggered right before a transaction is started | yii\mongodb\Connection |
Property Details
Default database name.
Options for the MongoDB driver. Any driver-specific options not included in MongoDB connection string specification.
See also http://php.net/manual/en/mongodb-driver-manager.construct.php.
Host:port
Correct syntax is: mongodb://[username:password@]host1[:port1][,host2[:port2:],...][/dbname] For example: mongodb://localhost:27017 mongodb://developer:password@localhost:27017 mongodb://developer:password@localhost:27017/mydatabase
Whether to log command and query executions. When enabled this option may reduce performance. MongoDB commands may contain large data, consuming both CPU and memory. It makes sense to disable this option in the production environment.
Whether to enable profiling the commands and queries being executed. This option will have no effect in case $enableLogging is disabled.
Mongo GridFS collection instance.
Name of the protocol, which should be used for the GridFS stream wrapper. Only alphanumeric values are allowed: do not use any URL special characters, such as '/', '&', ':' etc.
See also yii\mongodb\file\StreamWrapper.
Name of the class, which should serve as a stream wrapper for $fileStreamProtocol protocol.
Default options for executeCommand
, executeBulkWrite and executeQuery method of MongoDB\Driver\Manager in Command
class.
'share' => [],
'command' => [],
'bulkWrite' => [],
'query' => [],
]
Whether the Mongo connection is established.
The log builder for this connection. Note that the type of this property differs in getter and setter. See getLogBuilder() and setLogBuilder() for details.
MongoDB driver manager.
Connection options. For example:
[
'socketTimeoutMS' => 1000, // how long a send or receive on a socket can take before timing out
'ssl' => true // initiate the connection with TLS/SSL
]
See also https://docs.mongodb.com/manual/reference/connection-string/#connections-connection-options.
The query builder for the this MongoDB connection. Note that the type of this property differs in getter and setter. See getQueryBuilder() and setQueryBuilder() for details.
New instance of ClientSession to replace return $this.
Type map to use for BSON unserialization. Note: default type map will be automatically merged into this field, possibly overriding user-defined values.
See also http://php.net/manual/en/mongodb-driver-cursor.settypemap.php.
Method Details
Closes the currently active DB connection.
It does nothing if the connection is already closed.
public void close ( ) |
public function close()
{
if ($this->manager !== null) {
Yii::debug('Closing MongoDB connection: ' . $this->dsn, __METHOD__);
$this->manager = null;
foreach ($this->_databases as $database) {
$database->clearCollections();
}
$this->_databases = [];
}
}
Commits transaction in current session
public void commitTransaction ( ) |
public function commitTransaction()
{
$this->transactionReady('commit transaction');
$this->getSession()->transaction->commit();
}
Creates MongoDB command.
public yii\mongodb\Command createCommand ( $document = [], $databaseName = null ) | ||
$document | array |
Command document contents. |
$databaseName | string|null |
Database name, if not set $defaultDatabaseName will be used. |
return | yii\mongodb\Command |
Command instance. |
---|
public function createCommand($document = [], $databaseName = null)
{
return new Command([
'db' => $this,
'databaseName' => $databaseName,
'document' => $document,
'globalExecOptions' => $this->globalExecOptions
]);
}
Recursive replacement on $this->globalExecOptions with new options. {@see $this->globalExecOptions}
public $this execOptions ( $newExecOptions ) | ||
$newExecOptions | array |
{@see $this->globalExecOptions} |
public function execOptions($newExecOptions)
{
if (empty($newExecOptions)) {
$this->globalExecOptions = [];
}
else {
$this->globalExecOptions = array_replace_recursive($this->globalExecOptions, $newExecOptions);
}
return $this;
}
Returns the MongoDB collection with the given name.
public yii\mongodb\Collection getCollection ( $name, $refresh = false ) | ||
$name | string|array |
Collection name. If string considered as the name of the collection inside the default database. If array - first element considered as the name of the database, second - as name of collection inside that database |
$refresh | boolean |
Whether to reload the collection instance even if it is found in the cache. |
return | yii\mongodb\Collection |
Mongo collection instance. |
---|
public function getCollection($name, $refresh = false)
{
if (is_array($name)) {
list ($dbName, $collectionName) = $name;
return $this->getDatabase($dbName)->getCollection($collectionName, $refresh);
}
return $this->getDatabase()->getCollection($name, $refresh);
}
Returns the MongoDB database with the given name.
public yii\mongodb\Database getDatabase ( $name = null, $refresh = false ) | ||
$name | string|null |
Database name, if null default one will be used. |
$refresh | boolean |
Whether to reestablish the database connection even, if it is found in the cache. |
return | yii\mongodb\Database |
Database instance. |
---|
public function getDatabase($name = null, $refresh = false)
{
if ($name === null) {
$name = $this->getDefaultDatabaseName();
}
if ($refresh || !array_key_exists($name, $this->_databases)) {
$this->_databases[$name] = $this->selectDatabase($name);
}
return $this->_databases[$name];
}
Returns default database name, if it is not set, attempts to determine it from $dsn value.
public string getDefaultDatabaseName ( ) | ||
return | string |
Default database name |
---|---|---|
throws | \yii\base\InvalidConfigException |
if unable to determine default database name. |
public function getDefaultDatabaseName()
{
if ($this->_defaultDatabaseName === null) {
if (preg_match('/^mongodb:\\/\\/.+\\/([^?&]+)/s', $this->dsn, $matches)) {
$this->_defaultDatabaseName = $matches[1];
} else {
throw new InvalidConfigException("Unable to determine default database name from dsn.");
}
}
return $this->_defaultDatabaseName;
}
Returns the MongoDB GridFS collection.
public yii\mongodb\file\Collection getFileCollection ( $prefix = 'fs', $refresh = false ) | ||
$prefix | string|array |
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. |
$refresh | boolean |
Whether to reload the collection instance even if it is found in the cache. |
return | yii\mongodb\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);
}
return $this->getDatabase()->getFileCollection($prefix, $refresh);
}
Checks whether the current connection is in session.
return bool
public void getInSession ( ) |
public function getInSession()
{
return array_key_exists('session',$this->globalExecOptions['share']);
}
Checks that the current connection is in session and transaction return bool
public void getInTransaction ( ) |
public function getInTransaction()
{
return $this->getInSession() && $this->getSession()->getInTransaction();
}
Returns a value indicating whether the Mongo connection is established.
public boolean getIsActive ( ) | ||
return | boolean |
Whether the Mongo connection is established |
---|
public function getIsActive()
{
return is_object($this->manager) && $this->manager->getServers() !== [];
}
Returns log builder for this connection.
public yii\mongodb\LogBuilder getLogBuilder ( ) | ||
return | yii\mongodb\LogBuilder |
The log builder for this connection. |
---|
public function getLogBuilder()
{
if (!is_object($this->_logBuilder)) {
$this->_logBuilder = Yii::createObject($this->_logBuilder);
}
return $this->_logBuilder;
}
Returns the query builder for the this MongoDB connection.
public yii\mongodb\QueryBuilder getQueryBuilder ( ) | ||
return | yii\mongodb\QueryBuilder |
The query builder for the this MongoDB connection. |
---|
public function getQueryBuilder()
{
if (!is_object($this->_queryBuilder)) {
$this->_queryBuilder = Yii::createObject($this->_queryBuilder, [$this]);
}
return $this->_queryBuilder;
}
Returns current session return ClientSession|null
public void getSession ( ) |
public function getSession()
{
return $this->getInSession() ? $this->globalExecOptions['share']['session'] : null;
}
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 void initConnection ( ) |
protected function initConnection()
{
$this->trigger(self::EVENT_AFTER_OPEN);
}
Only starts the new session for current connection but this session does not set for current connection.
public void newSession ( $sessionOptions = [] ) | ||
$sessionOptions | array |
See doc of ClientSession::start() return ClientSession |
public function newSession($sessionOptions = [])
{
return ClientSession::start($this, $sessionOptions);
}
Runs your mongodb command out of session and transaction.
public mixed noTransaction ( callable $actions ) | ||
$actions | callable |
Your block of code must be runned out of session and transaction |
return | mixed |
Returns a result of $actions() |
---|
public function noTransaction(callable $actions)
{
$lastSession = $this->getSession();
$this->setSession(null);
try {
$result = $actions();
} finally {
$this->setSession($lastSession);
}
return $result;
}
Establishes a Mongo connection.
It does nothing if a MongoDB connection has already been established.
public void open ( ) | ||
throws | yii\mongodb\Exception |
if connection fails |
---|
public function open()
{
if ($this->manager === null) {
if (empty($this->dsn)) {
throw new InvalidConfigException($this->className() . '::dsn cannot be empty.');
}
$token = 'Opening MongoDB connection: ' . $this->dsn;
try {
Yii::debug($token, __METHOD__);
Yii::beginProfile($token, __METHOD__);
$options = $this->options;
$this->manager = new Manager($this->dsn, $options, $this->driverOptions);
$this->manager->selectServer($this->manager->getReadPreference());
$this->initConnection();
Yii::endProfile($token, __METHOD__);
} catch (\Exception $e) {
Yii::endProfile($token, __METHOD__);
throw new Exception($e->getMessage(), (int) $e->getCode(), $e);
}
$this->typeMap = array_merge(
$this->typeMap,
[
'root' => 'array',
'document' => 'array'
]
);
}
}
Registers GridFS stream wrapper for the $fileStreamProtocol protocol.
public string registerFileStreamWrapper ( $force = false ) | ||
$force | boolean |
Whether to enforce registration even wrapper has been already registered. |
return | string |
Registered stream protocol name. |
---|
public function registerFileStreamWrapper($force = false)
{
if ($force || !$this->_fileStreamWrapperRegistered) {
/* @var $class \yii\mongodb\file\StreamWrapper */
$class = $this->fileStreamWrapperClass;
$class::register($this->fileStreamProtocol, $force);
$this->_fileStreamWrapperRegistered = true;
}
return $this->fileStreamProtocol;
}
Rollbacks transaction in current session
public void rollBackTransaction ( ) |
public function rollBackTransaction()
{
$this->transactionReady('roll back transaction');
$this->getSession()->transaction->rollBack();
}
Selects the database with given name.
protected yii\mongodb\Database selectDatabase ( $name ) | ||
$name | string |
Database name. |
return | yii\mongodb\Database |
Database instance. |
---|
protected function selectDatabase($name)
{
return Yii::createObject([
'class' => 'yii\mongodb\Database',
'name' => $name,
'connection' => $this,
]);
}
Sets default database name.
public void setDefaultDatabaseName ( $name ) | ||
$name | string |
Default database name. |
public function setDefaultDatabaseName($name)
{
$this->_defaultDatabaseName = $name;
}
Sets log builder used for this connection.
public void setLogBuilder ( $logBuilder ) | ||
$logBuilder | array|string|yii\mongodb\LogBuilder |
The log builder for this connection. |
public function setLogBuilder($logBuilder)
{
$this->_logBuilder = $logBuilder;
}
Sets the query builder for the this MongoDB connection.
public void setQueryBuilder ( $queryBuilder ) | ||
$queryBuilder | yii\mongodb\QueryBuilder|array|string|null |
The query builder for this MongoDB connection. |
public function setQueryBuilder($queryBuilder)
{
$this->_queryBuilder = $queryBuilder;
}
Changes the current session of connection to execute commands (or drop session)
public void setSession ( $clientSession ) | ||
$clientSession | yii\mongodb\ClientSession|null |
New instance of ClientSession to replace return $this |
public function setSession($clientSession)
{
#drop session
if (empty($clientSession)) {
unset($this->globalExecOptions['share']['session']);
}
else {
$this->globalExecOptions['share']['session'] = $clientSession;
}
return $this;
}
Ends the previous session and starts the new session.
public void startSession ( $sessionOptions = [] ) | ||
$sessionOptions | array |
See doc of ClientSession::start() return ClientSession |
public function startSession($sessionOptions = [])
{
if ($this->getInSession()) {
$this->getSession()->end();
}
$newSession = $this->newSession($sessionOptions);
$this->setSession($newSession);
return $newSession;
}
Starts a new session if the session has not started, otherwise returns previous session.
public void startSessionOnce ( $sessionOptions = [] ) | ||
$sessionOptions | array |
See doc of ClientSession::start() return ClientSession |
public function startSessionOnce($sessionOptions = [])
{
if ($this->getInSession()) {
return $this->getSession();
}
return $this->startSession($sessionOptions);
}
Starts a transaction with three steps : - starts new session if has not started - starts the transaction in new session - sets new session to current connection
public void startTransaction ( $transactionOptions = [], $sessionOptions = [] ) | ||
$transactionOptions | array |
See doc of Transaction::start() |
$sessionOptions | array |
See doc of ClientSession::start() return ClientSession |
public function startTransaction($transactionOptions = [], $sessionOptions = [])
{
$session = $this->startSession($sessionOptions,true);
$session->getTransaction()->start($transactionOptions);
return $session;
}
Starts a transaction in current session if the previous transaction was not started in current session.
public void startTransactionOnce ( $transactionOptions = [], $sessionOptions = [] ) | ||
$transactionOptions | array |
See doc of Transaction::start() |
$sessionOptions | array |
See doc of ClientSession::start() return ClientSession |
public function startTransactionOnce($transactionOptions = [], $sessionOptions = [])
{
if ($this->getInTransaction()) {
return $this->getSession();
}
return $this->startTransaction($transactionOptions,$sessionOptions);
}
Starts and commits a transaction in easy mode.
public void transaction ( callable $actions, $transactionOptions = [], $sessionOptions = [] ) | ||
$actions | callable |
Your block of code must be runned after transaction started and before commit if the $actions returns false then transaction rolls back. |
$transactionOptions | array |
See doc of Transaction::start() |
$sessionOptions | array |
See doc of ClientSession::start() |
public function transaction(callable $actions, $transactionOptions = [], $sessionOptions = [])
{
$session = $this->startTransaction($transactionOptions, $sessionOptions);
$success = false;
try {
$result = call_user_func($actions, $session);
if ($session->getTransaction()->getIsActive()) {
if ($result === false) {
$session->getTransaction()->rollBack();
}
else {
$session->getTransaction()->commit();
}
}
$success = true;
} finally {
if (!$success && $session->getTransaction()->getIsActive()) {
$session->getTransaction()->rollBack();
}
}
}
Starts and commits transaction in easy mode if the previous transaction was not executed, otherwise only runs your actions in previous transaction.
public void transactionOnce ( callable $actions, $transactionOptions = [], $sessionOptions = [] ) | ||
$actions | callable |
Your block of code must be runned after transaction started and before commit |
$transactionOptions | array |
See doc of Transaction::start() |
$sessionOptions | array |
See doc of ClientSession::start() |
public function transactionOnce(callable $actions, $transactionOptions = [], $sessionOptions = [])
{
if ($this->getInTransaction()) {
$actions();
}
else {
$this->transaction($actions,$transactionOptions,$sessionOptions);
}
}
Throws custom error if transaction is not ready in connection
public void transactionReady ( $operation ) | ||
$operation | string |
A custom message to be shown |
public function transactionReady($operation)
{
if (!$this->getInSession()) {
throw new Exception('You can\'t ' . $operation . ' because current connection is\'t in a session.');
}
if (!$this->getSession()->getInTransaction()) {
throw new Exception('You can\'t ' . $operation . ' because transaction not started in current session.');
}
}
Event Details
An event that is triggered after a DB connection is established
An event that is triggered right after a transaction is committed
An event that is triggered right after a mongo client session is ended
An event that is triggered right after a transaction is rolled back
An event that is triggered right before a mongo client session is started