Connection represents a connection to a database via PDO.
Connection works together with yii\db\Command, yii\db\DataReader and yii\db\Transaction to provide data access to various DBMS in a common set of APIs. They are a thin wrapper of the PDO PHP extension.
Connection supports database replication and read-write splitting. In particular, a Connection component can be configured with multiple $masters and $slaves. It will do load balancing and failover by choosing appropriate servers. It will also automatically direct read operations to the slaves and write operations to the masters.
To establish a DB connection, set $dsn, $username and $password, and then call open() to connect to the database server. The current state of the connection can be checked using $isActive.
The following example shows how to create a Connection instance and establish the DB connection:
$connection = new \yii\db\Connection([
'dsn' => $dsn,
'username' => $username,
'password' => $password,
]);
$connection->open();
After the DB connection is established, one can execute SQL statements like the following:
$command = $connection->createCommand('SELECT * FROM post');
$posts = $command->queryAll();
$command = $connection->createCommand('UPDATE post SET status=1');
$command->execute();
One can also do prepared SQL execution and bind parameters to the prepared SQL. When the parameters are coming from user input, you should use this approach to prevent SQL injection attacks. The following is an example:
$command = $connection->createCommand('SELECT * FROM post WHERE id=:id');
$command->bindValue(':id', $_GET['id']);
$post = $command->query();
For more information about how to perform various DB queries, please refer to yii\db\Command.
If the underlying DBMS supports transactions, you can perform transactional SQL queries like the following:
$transaction = $connection->beginTransaction();
try {
$connection->createCommand($sql1)->execute();
$connection->createCommand($sql2)->execute();
$transaction->commit();
} catch (Exception $e) {
$transaction->rollBack();
}
You also can use shortcut for the above like the following:
$connection->transaction(function () {
$order = new Order($customer);
$order->save();
$order->addItems($items);
});
If needed you can pass transaction isolation level as a second parameter:
$connection->transaction(function (Connection $db) {
}, Transaction::READ_UNCOMMITTED);
Connection is often used as an application component and configured in the application configuration like the following:
'components' => [
'db' => [
'class' => '\yii\db\Connection',
'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
],
PDO attributes (name => value) that should be set when calling open() to establish a DB connection. Please refer to the PHP manual for details about available attributes.
The charset used for database connection. The property is only used for MySQL, PostgreSQL and CUBRID databases. Defaults to null, meaning using default charset as configured by the database.
For Oracle Database, the charset must be specified in the $dsn, for example for UTF-8 by appending ;charset=UTF-8
to the DSN string.
The same applies for if you're using GBK or BIG5 charset with MySQL, then it's highly recommended to specify charset via $dsn like 'mysql:dbname=mydatabase;host=127.0.0.1;charset=GBK;'
.
The class used to create new database yii\db\Command objects. If you want to extend the yii\db\Command class, you may configure this property to use your extended version of the class. Since version 2.0.14 $commandMap is used if this property is set to its default value.
See also createCommand().
Mapping between PDO driver names and yii\db\Command classes. The keys of the array are PDO driver names while the values are either the corresponding command class names or configurations. Please refer to Yii::createObject() for details on how to specify a configuration.
This property is mainly used by createCommand() to create new database yii\db\Command objects. You normally do not need to set this property unless you want to use your own yii\db\Command class or support DBMS that is not supported by Yii.
public array $commandMap = [The Data Source Name, or DSN, contains the information required to connect to the database. Please refer to the PHP manual on the format of the DSN string.
For SQLite you may use a path alias for specifying the database path, e.g. sqlite:@app/data/db.sql
.
See also $charset.
Whether to turn on prepare emulation. Defaults to false, meaning PDO will use the native prepare support if available. For some databases (such as MySQL), this may need to be set true so that PDO can emulate the prepare support to bypass the buggy native prepare support. The default value is null, which means the PDO ATTR_EMULATE_PREPARES value will not be changed.
Whether to enable logging of database queries. Defaults to true. You may want to disable this option in a production environment to gain performance if you do not need the information being logged.
See also $enableProfiling.
Whether to enable profiling of opening database connection and database queries. Defaults to true. You may want to disable this option in a production environment to gain performance if you do not need the information being logged.
See also $enableLogging.
Whether to enable savepoint. Note that if the underlying DBMS does not support savepoint, setting this property to be true will have no effect.
Whether to enable read/write splitting by using $slaves to read data. Note that if $slaves is empty, read/write splitting will NOT be enabled no matter what value this property takes.
Whether the DB connection is established.
If the database connected via pdo_dblib is SyBase.
The row ID of the last row inserted, or the last value retrieved from the sequence object.
The currently active master connection. null
is returned if there is no master available.
The configuration that should be merged with every master configuration listed in $masters. For example,
[
'username' => 'master',
'password' => 'master',
'attributes' => [
PDO::ATTR_TIMEOUT => 10,
],
]
The PDO instance for the currently active master connection.
List of master connection configurations. Each configuration is used to create a master DB connection. When open() is called, one of these configurations will be chosen and used to create a DB connection which will be used by this object. Note that when this property is not empty, the connection setting (e.g. "dsn", "username") of this object will be ignored.
See also:
The password for establishing DB connection. Defaults to null
meaning no password to use.
The PHP PDO instance associated with this DB connection. This property is mainly managed by open() and close() methods. When a DB connection is active, this property will represent a PDO instance; otherwise, it will be null.
See also $pdoClass.
The query builder for the current DB connection. Note that the type of this property differs in getter and setter. See getQueryBuilder() and setQueryBuilder() for details.
The cache object or the ID of the cache application component that is used for query caching.
See also $enableQueryCache.
The default number of seconds that query results can remain valid in cache. Defaults to 3600, meaning 3600 seconds, or one hour. Use 0 to indicate that the cached data will never expire. The value of this property will be used when cache() is called without a cache duration.
See also:
The schema information for the database opened by this connection.
The cache object or the ID of the cache application component that is used to cache the table metadata.
See also $enableSchemaCache.
Number of seconds that table metadata can remain valid in cache. Use 0 to indicate that the cached data will never expire.
See also $enableSchemaCache.
List of tables whose metadata should NOT be cached. Defaults to empty array. The table names may contain schema prefix, if any. Do not quote the table names.
See also $enableSchemaCache.
Mapping between PDO driver names and yii\db\Schema classes. The keys of the array are PDO driver names while the values are either the corresponding schema class names or configurations. Please refer to Yii::createObject() for details on how to specify a configuration.
This property is mainly used by getSchema() when fetching the database schema information. You normally do not need to set this property unless you want to use your own yii\db\Schema class to support DBMS that is not supported by Yii.
public array $schemaMap = [The cache object or the ID of the cache application component that is used to store the health status of the DB servers specified in $masters and $slaves. This is used only when read/write splitting is enabled or $masters is not empty. Set boolean false
to disabled server status caching.
See also:
Server version as a string.
The currently active slave connection. null
is returned if there is no slave available and $fallbackToMaster
is false.
The configuration that should be merged with every slave configuration listed in $slaves. For example,
[
'username' => 'slave',
'password' => 'slave',
'attributes' => [
PDO::ATTR_TIMEOUT => 10,
],
]
The PDO instance for the currently active slave connection. null
is returned if no slave connection is available and $fallbackToMaster
is false.
List of slave connection configurations. Each configuration is used to create a slave DB connection. When $enableSlaves is true, one of these configurations will be chosen and used to create a DB connection for performing read queries only.
See also:
The common prefix or suffix for table names. If a table name is given as {{%TableName}}
, then the percentage character %
will be replaced with this property value. For example, {{%post}}
becomes {{tbl_post}}
.
The currently active transaction. Null if no active transaction.
The username for establishing DB connection. Defaults to null
meaning no username to use.
Defined in: yii\base\Component::__call()
Calls the named method which is not a class method.
This method will check if any attached behavior has the named method and will execute it if available.
Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.
public function __call($name, $params)
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $object) {
if ($object->hasMethod($name)) {
return call_user_func_array([$object, $name], $params);
}
}
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
Reset the connection after cloning.
public function __clone()
{
parent::__clone();
$this->_master = false;
$this->_slave = false;
$this->_schema = null;
$this->_transaction = null;
if (strncmp($this->dsn, 'sqlite::memory:', 15) !== 0) {
$this->pdo = null;
}
}
Defined in: yii\base\BaseObject::__construct()
Constructor.
The default implementation does two things:
$config
.If this method is overridden in a child class, it is recommended that
$config
here.Name-value pairs that will be used to initialize the object properties
public function __construct($config = [])
{
if (!empty($config)) {
Yii::configure($this, $config);
}
$this->init();
}
Defined in: yii\base\Component::__get()
Returns the value of a component property.
This method will check in the following order and act accordingly:
Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $value = $component->property;
.
See also __set().
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter();
}
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name;
}
}
if (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::__isset()
Checks if a property is set, i.e. defined and not null.
This method will check in the following order and act accordingly:
false
for non existing propertiesDo not call this method directly as it is a PHP magic method that will be implicitly called when executing isset($component->property)
.
See also https://www.php.net/manual/en/function.isset.php.
public function __isset($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
}
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name !== null;
}
}
return false;
}
Defined in: yii\base\Component::__set()
Sets the value of a component property.
This method will check in the following order and act accordingly:
Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $component->property = $value;
.
See also __get().
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter($value);
return;
} elseif (strncmp($name, 'on ', 3) === 0) {
$this->on(trim(substr($name, 3)), $value);
return;
} elseif (strncmp($name, 'as ', 3) === 0) {
$name = trim(substr($name, 3));
if ($value instanceof Behavior) {
$this->attachBehavior($name, $value);
} elseif ($value instanceof \Closure) {
$this->attachBehavior($name, call_user_func($value));
} elseif (isset($value['__class']) && is_subclass_of($value['__class'], Behavior::class)) {
$this->attachBehavior($name, Yii::createObject($value));
} elseif (!isset($value['__class']) && isset($value['class']) && is_subclass_of($value['class'], Behavior::class)) {
$this->attachBehavior($name, Yii::createObject($value));
} elseif (is_string($value) && is_subclass_of($value, Behavior::class, true)) {
$this->attachBehavior($name, Yii::createObject($value));
} else {
throw new InvalidConfigException('Class is not of type ' . Behavior::class . ' or its subclasses');
}
return;
}
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = $value;
return;
}
}
if (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
Close the connection before serializing.
public function __sleep()
{
$fields = (array) $this;
unset($fields['pdo']);
unset($fields["\000" . __CLASS__ . "\000" . '_master']);
unset($fields["\000" . __CLASS__ . "\000" . '_slave']);
unset($fields["\000" . __CLASS__ . "\000" . '_transaction']);
unset($fields["\000" . __CLASS__ . "\000" . '_schema']);
return array_keys($fields);
}
Defined in: yii\base\Component::__unset()
Sets a component property to be null.
This method will check in the following order and act accordingly:
Do not call this method directly as it is a PHP magic method that will be implicitly called when executing unset($component->property)
.
See also https://www.php.net/manual/en/function.unset.php.
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
return;
}
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = null;
return;
}
}
throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
public void attachBehaviors ( $behaviors ) $behaviors array
List of behaviors to be attached to the component
public function attachBehaviors($behaviors)
{
$this->ensureBehaviors();
foreach ($behaviors as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
Starts a transaction.
public function beginTransaction($isolationLevel = null)
{
$this->open();
if (($transaction = $this->getTransaction()) === null) {
$transaction = $this->_transaction = new Transaction(['db' => $this]);
}
$transaction->begin($isolationLevel);
return $transaction;
}
Defined in: yii\base\Component::behaviors()
Returns a list of behaviors that this component should behave as.
Child classes may override this method to specify the behaviors they want to behave as.
The return value of this method should be an array of behavior objects or configurations indexed by behavior names. A behavior configuration can be either a string specifying the behavior class or an array of the following structure:
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
Note that a behavior class must extend from yii\base\Behavior. Behaviors can be attached using a name or anonymously. When a name is used as the array key, using this name, the behavior can later be retrieved using getBehavior() or be detached using detachBehavior(). Anonymous behaviors can not be retrieved or detached.
Behaviors declared in this method will be attached to the component automatically (on demand).
public function behaviors()
{
return [];
}
Uses query cache for the queries performed with the callable.
When query caching is enabled ($enableQueryCache is true and $queryCache refers to a valid cache), queries performed within the callable will be cached and their results will be fetched from cache if available. For example,
$customer = $db->cache(function (Connection $db) {
return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
});
Note that query cache is only meaningful for queries that return results. For queries performed with yii\db\Command::execute(), query cache will not be used.
See also:
public mixed cache ( callable $callable, $duration = null, $dependency = null ) $callable callableA PHP callable that contains DB queries which will make use of query cache. The signature of the callable is function (Connection $db)
.
The number of seconds that query results can remain valid in the cache. If this is not set, the value of $queryCacheDuration will be used instead. Use 0 to indicate that the cached data will never expire.
$dependency yii\caching\Dependency|nullThe cache dependency associated with the cached query results.
return mixedThe return result of the callable
throws Throwableif there is any exception during query
public function cache(callable $callable, $duration = null, $dependency = null)
{
$this->_queryCacheInfo[] = [$duration === null ? $this->queryCacheDuration : $duration, $dependency];
try {
$result = call_user_func($callable, $this);
array_pop($this->_queryCacheInfo);
return $result;
} catch (\Exception $e) {
array_pop($this->_queryCacheInfo);
throw $e;
} catch (\Throwable $e) {
array_pop($this->_queryCacheInfo);
throw $e;
}
}
Defined in: yii\base\Component::canGetProperty()
Returns a value indicating whether a property can be read.
A property can be read if:
$checkVars
is true);$checkBehaviors
is true).See also canSetProperty().
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) $name stringThe property name
$checkVars booleanWhether to treat member variables as properties
$checkBehaviors booleanWhether to treat behaviors' properties as properties of this component
return booleanWhether the property can be read
public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
Defined in: yii\base\Component::canSetProperty()
Returns a value indicating whether a property can be set.
A property can be written if:
$checkVars
is true);$checkBehaviors
is true).See also canGetProperty().
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) $name stringThe property name
$checkVars booleanWhether to treat member variables as properties
$checkBehaviors booleanWhether to treat behaviors' properties as properties of this component
return booleanWhether the property can be written
public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
Deprecated since 2.0.14. On PHP >=5.5, use ::class
instead.
public static function className()
{
return get_called_class();
}
Closes the currently active DB connection.
It does nothing if the connection is already closed.
public function close()
{
if ($this->_master) {
if ($this->pdo === $this->_master->pdo) {
$this->pdo = null;
}
$this->_master->close();
$this->_master = false;
}
if ($this->pdo !== null) {
Yii::debug('Closing DB connection: ' . $this->dsn, __METHOD__);
$this->pdo = null;
}
if ($this->_slave) {
$this->_slave->close();
$this->_slave = false;
}
$this->_schema = null;
$this->_transaction = null;
$this->_driverName = null;
$this->_queryCacheInfo = [];
$this->_quotedTableNames = null;
$this->_quotedColumnNames = null;
}
Creates a command for execution.
public function createCommand($sql = null, $params = [])
{
$driver = $this->getDriverName();
$config = ['class' => 'yii\db\Command'];
if ($this->commandClass !== $config['class']) {
$config['class'] = $this->commandClass;
} elseif (isset($this->commandMap[$driver])) {
$config = !is_array($this->commandMap[$driver]) ? ['class' => $this->commandMap[$driver]] : $this->commandMap[$driver];
}
$config['db'] = $this;
$config['sql'] = $sql;
$command = Yii::createObject($config);
return $command->bindValues($params);
}
Creates the PDO instance.
This method is called by open() to establish a DB connection. The default implementation will create a PHP PDO instance. You may override this method if the default PDO needs to be adapted for certain DBMS.
protected function createPdoInstance()
{
$pdoClass = $this->pdoClass;
if ($pdoClass === null) {
$driver = null;
if ($this->_driverName !== null) {
$driver = $this->_driverName;
} elseif (($pos = strpos($this->dsn, ':')) !== false) {
$driver = strtolower(substr($this->dsn, 0, $pos));
}
switch ($driver) {
case 'mssql':
$pdoClass = 'yii\db\mssql\PDO';
break;
case 'dblib':
$pdoClass = 'yii\db\mssql\DBLibPDO';
break;
case 'sqlsrv':
$pdoClass = 'yii\db\mssql\SqlsrvPDO';
break;
default:
$pdoClass = 'PDO';
}
}
$dsn = $this->dsn;
if (strncmp('sqlite:@', $dsn, 8) === 0) {
$dsn = 'sqlite:' . Yii::getAlias(substr($dsn, 7));
}
return new $pdoClass($dsn, $this->username, $this->password, $this->attributes);
}
public function detachBehavior($name)
{
$this->ensureBehaviors();
if (isset($this->_behaviors[$name])) {
$behavior = $this->_behaviors[$name];
unset($this->_behaviors[$name]);
$behavior->detach();
return $behavior;
}
return null;
}
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
public function ensureBehaviors()
{
if ($this->_behaviors === null) {
$this->_behaviors = [];
foreach ($this->behaviors() as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
}
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
Returns the name of the DB driver. Based on the the current $dsn, in case it was not set explicitly by an end user.
public function getDriverName()
{
if ($this->_driverName === null) {
if (($pos = strpos((string)$this->dsn, ':')) !== false) {
$this->_driverName = strtolower(substr($this->dsn, 0, $pos));
} else {
$this->_driverName = strtolower($this->getSlavePdo(true)->getAttribute(PDO::ATTR_DRIVER_NAME));
}
}
return $this->_driverName;
}
Returns a value indicating whether the DB connection is established.
public function getIsActive()
{
return $this->pdo !== null;
}
public string getLastInsertID ( $sequenceName = '' ) $sequenceName string
Name of the sequence object (required by some DBMS)
return stringThe row ID of the last row inserted, or the last value retrieved from the sequence object
public function getLastInsertID($sequenceName = '')
{
return $this->getSchema()->getLastInsertID($sequenceName);
}
Returns the currently active master connection.
If this method is called for the first time, it will try to open a master connection.
public function getMaster()
{
if ($this->_master === false) {
$this->_master = $this->shuffleMasters
? $this->openFromPool($this->masters, $this->masterConfig)
: $this->openFromPoolSequentially($this->masters, $this->masterConfig);
}
return $this->_master;
}
Returns the PDO instance for the currently active master connection.
This method will open the master DB connection and then return $pdo.
public PDO getMasterPdo ( ) return PDOThe PDO instance for the currently active master connection.
public function getMasterPdo()
{
$this->open();
return $this->pdo;
}
Returns the query builder for the current DB connection.
public function getQueryBuilder()
{
return $this->getSchema()->getQueryBuilder();
}
Returns the schema information for the database opened by this connection.
public function getSchema()
{
if ($this->_schema !== null) {
return $this->_schema;
}
$driver = $this->getDriverName();
if (isset($this->schemaMap[$driver])) {
$config = !is_array($this->schemaMap[$driver]) ? ['class' => $this->schemaMap[$driver]] : $this->schemaMap[$driver];
$config['db'] = $this;
$this->_schema = Yii::createObject($config);
$this->restoreQueryBuilderConfiguration();
return $this->_schema;
}
throw new NotSupportedException("Connection does not support reading schema information for '$driver' DBMS.");
}
Returns a server version as a string comparable by \version_compare().
public function getServerVersion()
{
return $this->getSchema()->getServerVersion();
}
Returns the currently active slave connection.
If this method is called for the first time, it will try to open a slave connection when $enableSlaves is true.
public yii\db\Connection|null getSlave ( $fallbackToMaster = true ) $fallbackToMaster booleanWhether to return a master connection in case there is no slave connection available.
return yii\db\Connection|nullThe currently active slave connection. null
is returned if there is no slave available and $fallbackToMaster
is false.
public function getSlave($fallbackToMaster = true)
{
if (!$this->enableSlaves) {
return $fallbackToMaster ? $this : null;
}
if ($this->_slave === false) {
$this->_slave = $this->openFromPool($this->slaves, $this->slaveConfig);
}
return $this->_slave === null && $fallbackToMaster ? $this : $this->_slave;
}
Returns the PDO instance for the currently active slave connection.
When $enableSlaves is true, one of the slaves will be used for read queries, and its PDO instance will be returned by this method.
public PDO|null getSlavePdo ( $fallbackToMaster = true ) $fallbackToMaster booleanWhether to return a master PDO in case none of the slave connections is available.
return PDO|nullThe PDO instance for the currently active slave connection. null
is returned if no slave connection is available and $fallbackToMaster
is false.
public function getSlavePdo($fallbackToMaster = true)
{
$db = $this->getSlave(false);
if ($db === null) {
return $fallbackToMaster ? $this->getMasterPdo() : null;
}
return $db->pdo;
}
Obtains the schema information for the named table.
public function getTableSchema($name, $refresh = false)
{
return $this->getSchema()->getTableSchema($name, $refresh);
}
Returns the currently active transaction.
public function getTransaction()
{
return $this->_transaction && $this->_transaction->getIsActive() ? $this->_transaction : null;
}
public function hasEventHandlers($name)
{
$this->ensureBehaviors();
if (!empty($this->_events[$name])) {
return true;
}
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
return true;
}
}
return Event::hasHandlers($this, $name);
}
Defined in: yii\base\Component::hasMethod()
Returns a value indicating whether a method is defined.
A method is defined if:
$checkBehaviors
is true).The property name
$checkBehaviors booleanWhether to treat behaviors' methods as methods of this component
return booleanWhether the method is defined
public function hasMethod($name, $checkBehaviors = true)
{
if (method_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->hasMethod($name)) {
return true;
}
}
}
return false;
}
Defined in: yii\base\Component::hasProperty()
Returns a value indicating whether a property is defined for this component.
A property is defined if:
$checkVars
is true);$checkBehaviors
is true).See also:
public boolean hasProperty ( $name, $checkVars = true, $checkBehaviors = true ) $name stringThe property name
$checkVars booleanWhether to treat member variables as properties
$checkBehaviors booleanWhether to treat behaviors' properties as properties of this component
return booleanWhether the property is defined
public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}
Defined in: yii\base\BaseObject::init()
Initializes the object.
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
public function init()
{
}
Initializes the DB connection.
This method is invoked right after the DB connection is established. The default implementation turns on PDO::ATTR_EMULATE_PREPARES
if $emulatePrepare is true, and sets the database $charset if it is not empty. It then triggers an EVENT_AFTER_OPEN event.
protected function initConnection()
{
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($this->emulatePrepare !== null && constant('PDO::ATTR_EMULATE_PREPARES')) {
if ($this->driverName !== 'sqlsrv') {
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare);
}
}
if (PHP_VERSION_ID >= 80100 && $this->getDriverName() === 'sqlite') {
$this->pdo->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, true);
}
if (!$this->isSybase && in_array($this->getDriverName(), ['mssql', 'dblib'], true)) {
$this->pdo->exec('SET ANSI_NULL_DFLT_ON ON');
}
if ($this->charset !== null && in_array($this->getDriverName(), ['pgsql', 'mysql', 'mysqli', 'cubrid'], true)) {
$this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset));
}
$this->trigger(self::EVENT_AFTER_OPEN);
}
Disables query cache temporarily.
Queries performed within the callable will not use query cache at all. For example,
$db->cache(function (Connection $db) {
return $db->noCache(function (Connection $db) {
return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
});
});
See also:
public mixed noCache ( callable $callable ) $callable callableA PHP callable that contains DB queries which should not use query cache. The signature of the callable is function (Connection $db)
.
The return result of the callable
throws Throwableif there is any exception during query
public function noCache(callable $callable)
{
$this->_queryCacheInfo[] = false;
try {
$result = call_user_func($callable, $this);
array_pop($this->_queryCacheInfo);
return $result;
} catch (\Exception $e) {
array_pop($this->_queryCacheInfo);
throw $e;
} catch (\Throwable $e) {
array_pop($this->_queryCacheInfo);
throw $e;
}
}
Defined in: yii\base\Component::off()
Detaches an existing event handler from this component.
This method is the opposite of on().
Note: in case wildcard pattern is passed for event name, only the handlers registered with this wildcard will be removed, while handlers registered with plain names matching this wildcard will remain.
See also on().
public boolean off ( $name, $handler = null ) $name stringEvent name
$handler callable|nullThe event handler to be removed. If it is null, all handlers attached to the named event will be removed.
return booleanIf a handler is found and detached
public function off($name, $handler = null)
{
$this->ensureBehaviors();
if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
return false;
}
if ($handler === null) {
unset($this->_events[$name], $this->_eventWildcards[$name]);
return true;
}
$removed = false;
if (isset($this->_events[$name])) {
foreach ($this->_events[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_events[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_events[$name] = array_values($this->_events[$name]);
return true;
}
}
if (isset($this->_eventWildcards[$name])) {
foreach ($this->_eventWildcards[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_eventWildcards[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
if (empty($this->_eventWildcards[$name])) {
unset($this->_eventWildcards[$name]);
}
}
}
return $removed;
}
Defined in: yii\base\Component::on()
Attaches an event handler to an event.
The event handler must be a valid PHP callback. The following are some examples:
function ($event) { ... }
[$object, 'handleClick']
['Page', 'handleClick']
'handleClick'
The event handler must be defined with the following signature,
function ($event)
where $event
is an yii\base\Event object which includes parameters associated with the event.
Since 2.0.14 you can specify event name as a wildcard pattern:
$component->on('event.group.*', function ($event) {
Yii::trace($event->name . ' is triggered.');
});
See also off().
public void on ( $name, $handler, $data = null, $append = true ) $name stringThe event name
$handler callableThe event handler
$data mixedThe data to be passed to the event handler when the event is triggered. When the event handler is invoked, this data can be accessed via yii\base\Event::$data.
$append booleanWhether to append new event handler to the end of the existing handler list. If false, the new handler will be inserted at the beginning of the existing handler list.
public function on($name, $handler, $data = null, $append = true)
{
$this->ensureBehaviors();
if (strpos($name, '*') !== false) {
if ($append || empty($this->_eventWildcards[$name])) {
$this->_eventWildcards[$name][] = [$handler, $data];
} else {
array_unshift($this->_eventWildcards[$name], [$handler, $data]);
}
return;
}
if ($append || empty($this->_events[$name])) {
$this->_events[$name][] = [$handler, $data];
} else {
array_unshift($this->_events[$name], [$handler, $data]);
}
}
Establishes a DB connection.
It does nothing if a DB connection has already been established.
public function open()
{
if ($this->pdo !== null) {
return;
}
if (!empty($this->masters)) {
$db = $this->getMaster();
if ($db !== null) {
$this->pdo = $db->pdo;
return;
}
throw new InvalidConfigException('None of the master DB servers is available.');
}
if (empty($this->dsn)) {
throw new InvalidConfigException('Connection::dsn cannot be empty.');
}
$token = 'Opening DB connection: ' . $this->dsn;
$enableProfiling = $this->enableProfiling;
try {
if ($this->enableLogging) {
Yii::info($token, __METHOD__);
}
if ($enableProfiling) {
Yii::beginProfile($token, __METHOD__);
}
$this->pdo = $this->createPdoInstance();
$this->initConnection();
if ($enableProfiling) {
Yii::endProfile($token, __METHOD__);
}
} catch (\PDOException $e) {
if ($enableProfiling) {
Yii::endProfile($token, __METHOD__);
}
throw new Exception($e->getMessage(), $e->errorInfo, $e->getCode(), $e);
}
}
Opens the connection to a server in the pool.
This method implements load balancing and failover among the given list of the servers. Connections will be tried in random order. For details about the failover behavior, see openFromPoolSequentially().
See also openFromPoolSequentially().
protected function openFromPool(array $pool, array $sharedConfig)
{
shuffle($pool);
return $this->openFromPoolSequentially($pool, $sharedConfig);
}
Opens the connection to a server in the pool.
This method implements failover among the given list of servers. Connections will be tried in sequential order. The first successful connection will return.
If $serverStatusCache is configured, this method will cache information about unreachable servers and does not try to connect to these for the time configured in $serverRetryInterval. This helps to keep the application stable when some servers are unavailable. Avoiding connection attempts to unavailable servers saves time when the connection attempts fail due to timeout.
If none of the servers are available the status cache is ignored and connection attempts are made to all servers (Since version 2.0.35). This is to avoid downtime when all servers are unavailable for a short time. After a successful connection attempt the server is marked as available again.
See also:
protected function openFromPoolSequentially(array $pool, array $sharedConfig)
{
if (empty($pool)) {
return null;
}
if (!isset($sharedConfig['class'])) {
$sharedConfig['class'] = get_class($this);
}
$cache = is_string($this->serverStatusCache) ? Yii::$app->get($this->serverStatusCache, false) : $this->serverStatusCache;
foreach ($pool as $i => $config) {
$pool[$i] = $config = array_merge($sharedConfig, $config);
if (empty($config['dsn'])) {
throw new InvalidConfigException('The "dsn" option must be specified.');
}
$key = [__METHOD__, $config['dsn']];
if ($cache instanceof CacheInterface && $cache->get($key)) {
continue;
}
$db = Yii::createObject($config);
try {
$db->open();
return $db;
} catch (\Exception $e) {
Yii::warning("Connection ({$config['dsn']}) failed: " . $e->getMessage(), __METHOD__);
if ($cache instanceof CacheInterface) {
$cache->set($key, 1, $this->serverRetryInterval);
}
unset($pool[$i]);
}
}
if ($cache instanceof CacheInterface) {
foreach ($pool as $config) {
$db = Yii::createObject($config);
try {
$db->open();
} catch (\Exception $e) {
Yii::warning("Connection ({$config['dsn']}) failed: " . $e->getMessage(), __METHOD__);
continue;
}
$cache->delete([__METHOD__, $config['dsn']]);
return $db;
}
}
return null;
}
Quotes a column name for use in a query.
If the column name contains prefix, the prefix will also be properly quoted. If the column name is already quoted or contains special characters including '(', '[[' and '{{', then this method will do nothing.
public function quoteColumnName($name)
{
if (isset($this->_quotedColumnNames[$name])) {
return $this->_quotedColumnNames[$name];
}
return $this->_quotedColumnNames[$name] = $this->getSchema()->quoteColumnName($name);
}
Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
Tokens enclosed within double curly brackets are treated as table names, while tokens enclosed within double square brackets are column names. They will be quoted accordingly. Also, the percentage character "%" at the beginning or ending of a table name will be replaced with $tablePrefix.
public function quoteSql($sql)
{
return preg_replace_callback(
'/(\\{\\{(%?[\w\-\. ]+%?)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/',
function ($matches) {
if (isset($matches[3])) {
return $this->quoteColumnName($matches[3]);
}
return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
},
$sql
);
}
Quotes a table name for use in a query.
If the table name contains schema prefix, the prefix will also be properly quoted. If the table name is already quoted or contains special characters including '(', '[[' and '{{', then this method will do nothing.
public function quoteTableName($name)
{
if (isset($this->_quotedTableNames[$name])) {
return $this->_quotedTableNames[$name];
}
return $this->_quotedTableNames[$name] = $this->getSchema()->quoteTableName($name);
}
public function quoteValue($value)
{
return $this->getSchema()->quoteValue($value);
}
Changes the current driver name.
public function setDriverName($driverName)
{
$this->_driverName = strtolower($driverName);
}
Can be used to set yii\db\QueryBuilder configuration via Connection configuration array.
public function setQueryBuilder($value)
{
Yii::configure($this->getQueryBuilder(), $value);
$this->_queryBuilderConfigurations[] = $value;
}
Executes callback provided in a transaction.
public mixed transaction ( callable $callback, $isolationLevel = null ) $callback callableA valid PHP callback that performs the job. Accepts connection instance as parameter.
$isolationLevel string|nullThe isolation level to use for this transaction. See yii\db\Transaction::begin() for details.
return mixedResult of callback function
throws Throwableif there is any exception during query. In this case the transaction will be rolled back.
public function transaction(callable $callback, $isolationLevel = null)
{
$transaction = $this->beginTransaction($isolationLevel);
$level = $transaction->level;
try {
$result = call_user_func($callback, $this);
if ($transaction->isActive && $transaction->level === $level) {
$transaction->commit();
}
} catch (\Exception $e) {
$this->rollbackTransactionOnLevel($transaction, $level);
throw $e;
} catch (\Throwable $e) {
$this->rollbackTransactionOnLevel($transaction, $level);
throw $e;
}
return $result;
}
Defined in: yii\base\Component::trigger()
Triggers an event.
This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.
public function trigger($name, ?Event $event = null)
{
$this->ensureBehaviors();
$eventHandlers = [];
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (StringHelper::matchWildcard($wildcard, $name)) {
$eventHandlers[] = $handlers;
}
}
if (!empty($this->_events[$name])) {
$eventHandlers[] = $this->_events[$name];
}
if (!empty($eventHandlers)) {
$eventHandlers = call_user_func_array('array_merge', $eventHandlers);
if ($event === null) {
$event = new Event();
}
if ($event->sender === null) {
$event->sender = $this;
}
$event->handled = false;
$event->name = $name;
foreach ($eventHandlers as $handler) {
$event->data = $handler[1];
call_user_func($handler[0], $event);
if ($event->handled) {
return;
}
}
}
Event::trigger($this, $name, $event);
}
Executes the provided callback by using the master connection.
This method is provided so that you can temporarily force using the master connection to perform DB operations even if they are read queries. For example,
$result = $db->useMaster(function ($db) {
return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
});
public mixed useMaster ( callable $callback ) $callback callable
A PHP callable to be executed by this method. Its signature is function (Connection $db)
. Its return value will be returned by this method.
The return value of the callback
throws Throwableif there is any exception thrown from the callback
public function useMaster(callable $callback)
{
if ($this->enableSlaves) {
$this->enableSlaves = false;
try {
$result = call_user_func($callback, $this);
} catch (\Exception $e) {
$this->enableSlaves = true;
throw $e;
} catch (\Throwable $e) {
$this->enableSlaves = true;
throw $e;
}
$this->enableSlaves = true;
} else {
$result = call_user_func($callback, $this);
}
return $result;
}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4