Connection
extends Component
in package
Connection represents a connection to a database via [PDO](https://www.php.net/manual/en/book.pdo.php).
Connection works together with [[Command]], [[DataReader]] and [[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 [[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();
// ... executing other SQL statements ...
$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) {
//return $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',
],
],
Tags
Table of Contents
Constants
- EVENT_AFTER_OPEN = 'afterOpen'
- EVENT_BEGIN_TRANSACTION = 'beginTransaction'
- EVENT_COMMIT_TRANSACTION = 'commitTransaction'
- EVENT_ROLLBACK_TRANSACTION = 'rollbackTransaction'
Properties
- $attributes : array<string|int, mixed>
- $behaviors : array<string|int, Behavior>
- $charset : string|null
- $commandClass : string
- $commandMap : array<string|int, mixed>
- $driverName : string|null
- $dsn : string
- $emulatePrepare : bool|null
- $enableLogging : bool
- $enableProfiling : bool
- $enableQueryCache : bool
- $enableSavepoint : bool
- $enableSchemaCache : bool
- $enableSlaves : bool
- $isActive : bool
- $isSybase : bool
- $lastInsertID : string
- $master : Connection|null
- $masterConfig : array<string|int, mixed>
- $masterPdo : PDO
- $masters : array<string|int, mixed>
- $password : string|null
- $pdo : PDO|null
- $pdoClass : string|null
- $queryBuilder : QueryBuilder
- $queryCache : CacheInterface|string
- $queryCacheDuration : int
- $schema : Schema
- $schemaCache : CacheInterface|string
- $schemaCacheDuration : int
- $schemaCacheExclude : array<string|int, mixed>
- $schemaMap : array<string|int, mixed>
- $serverRetryInterval : int
- $serverStatusCache : CacheInterface|string|false
- $serverVersion : string
- $shuffleMasters : bool
- $slave : Connection|null
- $slaveConfig : array<string|int, mixed>
- $slavePdo : PDO|null
- $slaves : array<string|int, mixed>
- $tablePrefix : string
- $transaction : Transaction|null
- $username : string|null
- $_behaviors : array<string|int, Behavior>|null
- $_driverName : string
- $_events : array<string|int, mixed>
- $_eventWildcards : array<string|int, mixed>
- $_master : Connection|false
- $_queryBuilderConfigurations : array<string|int, mixed>
- $_queryCacheInfo : array<string|int, mixed>
- $_quotedColumnNames : array<string|int, string>
- $_quotedTableNames : array<string|int, string>
- $_schema : Schema
- $_slave : Connection|false
- $_transaction : Transaction
Methods
- __call() : mixed
- Calls the named method which is not a class method.
- __clone() : mixed
- Reset the connection after cloning.
- __construct() : mixed
- Constructor.
- __get() : mixed
- Returns the value of a component property.
- __isset() : bool
- Checks if a property is set, i.e. defined and not null.
- __set() : mixed
- Sets the value of a component property.
- __sleep() : array<string|int, mixed>
- Close the connection before serializing.
- __unset() : mixed
- Sets a component property to be null.
- attachBehavior() : Behavior
- Attaches a behavior to this component.
- attachBehaviors() : mixed
- Attaches a list of behaviors to the component.
- beginTransaction() : Transaction
- Starts a transaction.
- behaviors() : array<string|int, mixed>
- Returns a list of behaviors that this component should behave as.
- cache() : mixed
- Uses query cache for the queries performed with the callable.
- canGetProperty() : bool
- Returns a value indicating whether a property can be read.
- canSetProperty() : bool
- Returns a value indicating whether a property can be set.
- className() : string
- Returns the fully qualified name of this class.
- close() : mixed
- Closes the currently active DB connection.
- createCommand() : Command
- Creates a command for execution.
- detachBehavior() : Behavior|null
- Detaches a behavior from the component.
- detachBehaviors() : mixed
- Detaches all behaviors from the component.
- ensureBehaviors() : mixed
- Makes sure that the behaviors declared in [[behaviors()]] are attached to this component.
- getBehavior() : Behavior|null
- Returns the named behavior object.
- getBehaviors() : array<string|int, Behavior>
- Returns all behaviors attached to this component.
- getDriverName() : string|null
- Returns the name of the DB driver. Based on the the current [[dsn]], in case it was not set explicitly by an end user.
- getIsActive() : bool
- Returns a value indicating whether the DB connection is established.
- getLastInsertID() : string
- Returns the ID of the last inserted row or sequence value.
- getMaster() : Connection|null
- Returns the currently active master connection.
- getMasterPdo() : PDO
- Returns the PDO instance for the currently active master connection.
- getQueryBuilder() : QueryBuilder
- Returns the query builder for the current DB connection.
- getSchema() : Schema
- Returns the schema information for the database opened by this connection.
- getServerVersion() : string
- Returns a server version as a string comparable by [[\version_compare()]].
- getSlave() : Connection|null
- Returns the currently active slave connection.
- getSlavePdo() : PDO|null
- Returns the PDO instance for the currently active slave connection.
- getTableSchema() : TableSchema|null
- Obtains the schema information for the named table.
- getTransaction() : Transaction|null
- Returns the currently active transaction.
- hasEventHandlers() : bool
- Returns a value indicating whether there is any handler attached to the named event.
- hasMethod() : bool
- Returns a value indicating whether a method is defined.
- hasProperty() : bool
- Returns a value indicating whether a property is defined for this component.
- init() : mixed
- Initializes the object.
- noCache() : mixed
- Disables query cache temporarily.
- off() : bool
- Detaches an existing event handler from this component.
- on() : mixed
- Attaches an event handler to an event.
- open() : mixed
- Establishes a DB connection.
- quoteColumnName() : string
- Quotes a column name for use in a query.
- quoteSql() : string
- Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
- quoteTableName() : string
- Quotes a table name for use in a query.
- quoteValue() : string
- Quotes a string value for use in a query.
- setDriverName() : mixed
- Changes the current driver name.
- setQueryBuilder() : mixed
- Can be used to set [[QueryBuilder]] configuration via Connection configuration array.
- transaction() : mixed
- Executes callback provided in a transaction.
- trigger() : mixed
- Triggers an event.
- useMaster() : mixed
- Executes the provided callback by using the master connection.
- createPdoInstance() : PDO
- Creates the PDO instance.
- initConnection() : mixed
- Initializes the DB connection.
- openFromPool() : Connection|null
- Opens the connection to a server in the pool.
- openFromPoolSequentially() : Connection|null
- Opens the connection to a server in the pool.
- attachBehaviorInternal() : Behavior
- Attaches a behavior to this component.
- restoreQueryBuilderConfiguration() : mixed
- Restores custom QueryBuilder configuration after the connection close/open cycle
- rollbackTransactionOnLevel() : mixed
- Rolls back given [[Transaction]] object if it's still active and level match.
Constants
EVENT_AFTER_OPEN
public
mixed
EVENT_AFTER_OPEN
= 'afterOpen'
Tags
EVENT_BEGIN_TRANSACTION
public
mixed
EVENT_BEGIN_TRANSACTION
= 'beginTransaction'
Tags
EVENT_COMMIT_TRANSACTION
public
mixed
EVENT_COMMIT_TRANSACTION
= 'commitTransaction'
Tags
EVENT_ROLLBACK_TRANSACTION
public
mixed
EVENT_ROLLBACK_TRANSACTION
= 'rollbackTransaction'
Tags
Properties
$attributes
public
array<string|int, mixed>
$attributes
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.
$behaviors read-only
public
array<string|int, Behavior>
$behaviors
List of behaviors attached to this component.
$charset
public
string|null
$charset
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;'
.
$commandClass
public
string
$commandClass
= 'yii\db\Command'
the class used to create new database [[Command]] objects. If you want to extend the [[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.
Tags
$commandMap
public
array<string|int, mixed>
$commandMap
= [
'pgsql' => 'yii\db\Command',
// PostgreSQL
'mysqli' => 'yii\db\Command',
// MySQL
'mysql' => 'yii\db\Command',
// MySQL
'sqlite' => 'yii\db\sqlite\Command',
// sqlite 3
'sqlite2' => 'yii\db\sqlite\Command',
// sqlite 2
'sqlsrv' => 'yii\db\Command',
// newer MSSQL driver on MS Windows hosts
'oci' => 'yii\db\oci\Command',
// Oracle driver
'mssql' => 'yii\db\Command',
// older MSSQL driver on MS Windows hosts
'dblib' => 'yii\db\Command',
// dblib drivers on GNU/Linux (and maybe other OSes) hosts
'cubrid' => 'yii\db\Command',
]
mapping between PDO driver names and [[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 [[Command]] objects. You normally do not need to set this property unless you want to use your own [[Command]] class or support DBMS that is not supported by Yii.
Tags
$driverName
public
string|null
$driverName
Name of the DB driver. Note that the type of this property differs in getter and setter. See [[getDriverName()]] and [[setDriverName()]] for details.
$dsn
public
string
$dsn
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
.
Tags
$emulatePrepare
public
bool|null
$emulatePrepare
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.
$enableLogging
public
bool
$enableLogging
= true
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.
Tags
$enableProfiling
public
bool
$enableProfiling
= true
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.
Tags
$enableQueryCache
public
bool
$enableQueryCache
= true
whether to enable query caching. Note that in order to enable query caching, a valid cache component as specified by [[queryCache]] must be enabled and [[enableQueryCache]] must be set true. Also, only the results of the queries enclosed within [[cache()]] will be cached.
Tags
$enableSavepoint
public
bool
$enableSavepoint
= true
whether to enable savepoint. Note that if the underlying DBMS does not support savepoint, setting this property to be true will have no effect.
$enableSchemaCache
public
bool
$enableSchemaCache
= false
whether to enable schema caching. Note that in order to enable truly schema caching, a valid cache component as specified by [[schemaCache]] must be enabled and [[enableSchemaCache]] must be set true.
Tags
$enableSlaves
public
bool
$enableSlaves
= true
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.
$isActive read-only
public
bool
$isActive
Whether the DB connection is established.
$isSybase
public
bool
$isSybase
= false
If the database connected via pdo_dblib is SyBase.
Tags
$lastInsertID read-only
public
string
$lastInsertID
The row ID of the last row inserted, or the last value retrieved from the sequence object.
$master read-only
public
Connection|null
$master
The currently active master connection. null
is returned if there
is no master available.
$masterConfig
public
array<string|int, mixed>
$masterConfig
= []
the configuration that should be merged with every master configuration listed in [[masters]]. For example,
[
'username' => 'master',
'password' => 'master',
'attributes' => [
// use a smaller connection timeout
PDO::ATTR_TIMEOUT => 10,
],
]
$masterPdo read-only
public
PDO
$masterPdo
The PDO instance for the currently active master connection.
$masters
public
array<string|int, mixed>
$masters
= []
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.
Tags
$password
public
string|null
$password
the password for establishing DB connection. Defaults to null
meaning no password to use.
$pdo
public
PDO|null
$pdo
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.
Tags
$pdoClass
public
string|null
$pdoClass
Custom PDO wrapper class. If not set, it will use [[PDO]] or [[\yii\db\mssql\PDO]] when MSSQL is used.
Tags
$queryBuilder
public
QueryBuilder
$queryBuilder
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.
$queryCache
public
CacheInterface|string
$queryCache
= 'cache'
the cache object or the ID of the cache application component that is used for query caching.
Tags
$queryCacheDuration
public
int
$queryCacheDuration
= 3600
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.
Tags
$schema read-only
public
Schema
$schema
The schema information for the database opened by this connection.
$schemaCache
public
CacheInterface|string
$schemaCache
= 'cache'
the cache object or the ID of the cache application component that is used to cache the table metadata.
Tags
$schemaCacheDuration
public
int
$schemaCacheDuration
= 3600
number of seconds that table metadata can remain valid in cache. Use 0 to indicate that the cached data will never expire.
Tags
$schemaCacheExclude
public
array<string|int, mixed>
$schemaCacheExclude
= []
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.
Tags
$schemaMap
public
array<string|int, mixed>
$schemaMap
= [
'pgsql' => 'yii\db\pgsql\Schema',
// PostgreSQL
'mysqli' => 'yii\db\mysql\Schema',
// MySQL
'mysql' => 'yii\db\mysql\Schema',
// MySQL
'sqlite' => 'yii\db\sqlite\Schema',
// sqlite 3
'sqlite2' => 'yii\db\sqlite\Schema',
// sqlite 2
'sqlsrv' => 'yii\db\mssql\Schema',
// newer MSSQL driver on MS Windows hosts
'oci' => 'yii\db\oci\Schema',
// Oracle driver
'mssql' => 'yii\db\mssql\Schema',
// older MSSQL driver on MS Windows hosts
'dblib' => 'yii\db\mssql\Schema',
// dblib drivers on GNU/Linux (and maybe other OSes) hosts
'cubrid' => 'yii\db\cubrid\Schema',
]
mapping between PDO driver names and [[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 [[Schema]] class to support DBMS that is not supported by Yii.
$serverRetryInterval
public
int
$serverRetryInterval
= 600
the retry interval in seconds for dead servers listed in [[masters]] and [[slaves]]. This is used together with [[serverStatusCache]].
$serverStatusCache
public
CacheInterface|string|false
$serverStatusCache
= 'cache'
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.
Tags
$serverVersion read-only
public
string
$serverVersion
Server version as a string.
$shuffleMasters
public
bool
$shuffleMasters
= true
whether to shuffle [[masters]] before getting one.
Tags
$slave read-only
public
Connection|null
$slave
The currently active slave connection. null
is returned if there is
no slave available and $fallbackToMaster
is false.
$slaveConfig
public
array<string|int, mixed>
$slaveConfig
= []
the configuration that should be merged with every slave configuration listed in [[slaves]]. For example,
[
'username' => 'slave',
'password' => 'slave',
'attributes' => [
// use a smaller connection timeout
PDO::ATTR_TIMEOUT => 10,
],
]
$slavePdo read-only
public
PDO|null
$slavePdo
The PDO instance for the currently active slave connection. null
is
returned if no slave connection is available and $fallbackToMaster
is false.
$slaves
public
array<string|int, mixed>
$slaves
= []
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.
Tags
$tablePrefix
public
string
$tablePrefix
= ''
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}}
.
$transaction read-only
public
Transaction|null
$transaction
The currently active transaction. Null if no active transaction.
$username
public
string|null
$username
the username for establishing DB connection. Defaults to null
meaning no username to use.
$_behaviors
private
array<string|int, Behavior>|null
$_behaviors
the attached behaviors (behavior name => behavior). This is null
when not initialized.
$_driverName
private
string
$_driverName
driver name
$_events
private
array<string|int, mixed>
$_events
= []
the attached event handlers (event name => handlers)
$_eventWildcards
private
array<string|int, mixed>
$_eventWildcards
= []
the event handlers attached for wildcard patterns (event name wildcard => handlers)
Tags
$_master
private
Connection|false
$_master
= false
the currently active master connection
$_queryBuilderConfigurations
private
array<string|int, mixed>
$_queryBuilderConfigurations
= []
An array of [[setQueryBuilder()]] calls, holding the passed arguments. Is used to restore a QueryBuilder configuration after the connection close/open cycle.
Tags
$_queryCacheInfo
private
array<string|int, mixed>
$_queryCacheInfo
= []
query cache parameters for the [[cache()]] calls
$_quotedColumnNames
private
array<string|int, string>
$_quotedColumnNames
quoted column name cache for [[quoteColumnName()]] calls
$_quotedTableNames
private
array<string|int, string>
$_quotedTableNames
quoted table name cache for [[quoteTableName()]] calls
$_schema
private
Schema
$_schema
the database schema
$_slave
private
Connection|false
$_slave
= false
the currently active slave connection
$_transaction
private
Transaction
$_transaction
the currently active transaction
Methods
__call()
Calls the named method which is not a class method.
public
__call(string $name, array<string|int, mixed> $params) : mixed
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.
Parameters
- $name : string
-
the method name
- $params : array<string|int, mixed>
-
method parameters
Tags
Return values
mixed —the method return value
__clone()
Reset the connection after cloning.
public
__clone() : mixed
__construct()
Constructor.
public
__construct([array<string|int, mixed> $config = [] ]) : mixed
The default implementation does two things:
- Initializes the object with the given configuration
$config
. - Call [[init()]].
If this method is overridden in a child class, it is recommended that
- the last parameter of the constructor is a configuration array, like
$config
here. - call the parent implementation at the end of the constructor.
Parameters
- $config : array<string|int, mixed> = []
-
name-value pairs that will be used to initialize the object properties
__get()
Returns the value of a component property.
public
__get(string $name) : mixed
This method will check in the following order and act accordingly:
- a property defined by a getter: return the getter result
- a property of a behavior: return the behavior property value
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $value = $component->property;
.
Parameters
- $name : string
-
the property name
Tags
Return values
mixed —the property value or the value of a behavior's property
__isset()
Checks if a property is set, i.e. defined and not null.
public
__isset(string $name) : bool
This method will check in the following order and act accordingly:
- a property defined by a setter: return whether the property is set
- a property of a behavior: return whether the property is set
- return
false
for non existing properties
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing isset($component->property)
.
Parameters
- $name : string
-
the property name or the event name
Tags
Return values
bool —whether the named property is set
__set()
Sets the value of a component property.
public
__set(string $name, mixed $value) : mixed
This method will check in the following order and act accordingly:
- a property defined by a setter: set the property value
- an event in the format of "on xyz": attach the handler to the event "xyz"
- a behavior in the format of "as xyz": attach the behavior named as "xyz"
- a property of a behavior: set the behavior property value
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $component->property = $value;
.
Parameters
- $name : string
-
the property name or the event name
- $value : mixed
-
the property value
Tags
__sleep()
Close the connection before serializing.
public
__sleep() : array<string|int, mixed>
Return values
array<string|int, mixed>__unset()
Sets a component property to be null.
public
__unset(string $name) : mixed
This method will check in the following order and act accordingly:
- a property defined by a setter: set the property value to be null
- a property of a behavior: set the property value to be null
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing unset($component->property)
.
Parameters
- $name : string
-
the property name
Tags
attachBehavior()
Attaches a behavior to this component.
public
attachBehavior(string $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior
This method will create the behavior object based on the given configuration. After that, the behavior object will be attached to this component by calling the [[Behavior::attach()]] method.
Parameters
- $name : string
-
the name of the behavior.
- $behavior : string|array<string|int, mixed>|Behavior
-
the behavior configuration. This can be one of the following:
- a [[Behavior]] object
- a string specifying the behavior class
- an object configuration array that will be passed to [[Yii::createObject()]] to create the behavior object.
Tags
Return values
Behavior —the behavior object
attachBehaviors()
Attaches a list of behaviors to the component.
public
attachBehaviors(array<string|int, mixed> $behaviors) : mixed
Each behavior is indexed by its name and should be a [[Behavior]] object, a string specifying the behavior class, or an configuration array for creating the behavior.
Parameters
- $behaviors : array<string|int, mixed>
-
list of behaviors to be attached to the component
Tags
beginTransaction()
Starts a transaction.
public
beginTransaction([string|null $isolationLevel = null ]) : Transaction
Parameters
- $isolationLevel : string|null = null
-
The isolation level to use for this transaction. See [[Transaction::begin()]] for details.
Return values
Transaction —the transaction initiated
behaviors()
Returns a list of behaviors that this component should behave as.
public
behaviors() : array<string|int, mixed>
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 [[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).
Return values
array<string|int, mixed> —the behavior configurations.
cache()
Uses query cache for the queries performed with the callable.
public
cache(callable $callable[, int|null $duration = null ][, Dependency|null $dependency = null ]) : mixed
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,
// The customer will be fetched from cache if available.
// If not, the query will be made against DB and cached for use next time.
$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 [[Command::execute()]], query cache will not be used.
Parameters
- $callable : callable
-
a PHP callable that contains DB queries which will make use of query cache. The signature of the callable is
function (Connection $db)
. - $duration : int|null = null
-
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 : Dependency|null = null
-
the cache dependency associated with the cached query results.
Tags
Return values
mixed —the return result of the callable
canGetProperty()
Returns a value indicating whether a property can be read.
public
canGetProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool
A property can be read if:
- the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a readable property of the given name (when
$checkBehaviors
is true).
Parameters
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
- $checkBehaviors : bool = true
-
whether to treat behaviors' properties as properties of this component
Tags
Return values
bool —whether the property can be read
canSetProperty()
Returns a value indicating whether a property can be set.
public
canSetProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool
A property can be written if:
- the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a writable property of the given name (when
$checkBehaviors
is true).
Parameters
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
- $checkBehaviors : bool = true
-
whether to treat behaviors' properties as properties of this component
Tags
Return values
bool —whether the property can be written
className()
Returns the fully qualified name of this class.
public
static className() : string
Tags
Return values
string —the fully qualified name of this class.
close()
Closes the currently active DB connection.
public
close() : mixed
It does nothing if the connection is already closed.
createCommand()
Creates a command for execution.
public
createCommand([string|null $sql = null ][, array<string|int, mixed> $params = [] ]) : Command
Parameters
- $sql : string|null = null
-
the SQL statement to be executed
- $params : array<string|int, mixed> = []
-
the parameters to be bound to the SQL statement
Return values
Command —the DB command
detachBehavior()
Detaches a behavior from the component.
public
detachBehavior(string $name) : Behavior|null
The behavior's [[Behavior::detach()]] method will be invoked.
Parameters
- $name : string
-
the behavior's name.
Return values
Behavior|null —the detached behavior. Null if the behavior does not exist.
detachBehaviors()
Detaches all behaviors from the component.
public
detachBehaviors() : mixed
ensureBehaviors()
Makes sure that the behaviors declared in [[behaviors()]] are attached to this component.
public
ensureBehaviors() : mixed
getBehavior()
Returns the named behavior object.
public
getBehavior(string $name) : Behavior|null
Parameters
- $name : string
-
the behavior name
Return values
Behavior|null —the behavior object, or null if the behavior does not exist
getBehaviors()
Returns all behaviors attached to this component.
public
getBehaviors() : array<string|int, Behavior>
Return values
array<string|int, Behavior> —list of behaviors attached to this component
getDriverName()
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
getDriverName() : string|null
Return values
string|null —name of the DB driver
getIsActive()
Returns a value indicating whether the DB connection is established.
public
getIsActive() : bool
Return values
bool —whether the DB connection is established
getLastInsertID()
Returns the ID of the last inserted row or sequence value.
public
getLastInsertID([string $sequenceName = '' ]) : string
Parameters
- $sequenceName : string = ''
-
name of the sequence object (required by some DBMS)
Tags
Return values
string —the row ID of the last row inserted, or the last value retrieved from the sequence object
getMaster()
Returns the currently active master connection.
public
getMaster() : Connection|null
If this method is called for the first time, it will try to open a master connection.
Tags
Return values
Connection|null —the currently active master connection. null
is returned if there is no master available.
getMasterPdo()
Returns the PDO instance for the currently active master connection.
public
getMasterPdo() : PDO
This method will open the master DB connection and then return [[pdo]].
Return values
PDO —the PDO instance for the currently active master connection.
getQueryBuilder()
Returns the query builder for the current DB connection.
public
getQueryBuilder() : QueryBuilder
Return values
QueryBuilder —the query builder for the current DB connection.
getSchema()
Returns the schema information for the database opened by this connection.
public
getSchema() : Schema
Tags
Return values
Schema —the schema information for the database opened by this connection.
getServerVersion()
Returns a server version as a string comparable by [[\version_compare()]].
public
getServerVersion() : string
Tags
Return values
string —server version as a string.
getSlave()
Returns the currently active slave connection.
public
getSlave([bool $fallbackToMaster = true ]) : Connection|null
If this method is called for the first time, it will try to open a slave connection when [[enableSlaves]] is true.
Parameters
- $fallbackToMaster : bool = true
-
whether to return a master connection in case there is no slave connection available.
Return values
Connection|null —the currently active slave connection. null
is returned if there is no slave available and
$fallbackToMaster
is false.
getSlavePdo()
Returns the PDO instance for the currently active slave connection.
public
getSlavePdo([bool $fallbackToMaster = true ]) : PDO|null
When [[enableSlaves]] is true, one of the slaves will be used for read queries, and its PDO instance will be returned by this method.
Parameters
- $fallbackToMaster : bool = true
-
whether to return a master PDO in case none of the slave connections is available.
Return values
PDO|null —the PDO instance for the currently active slave connection. null
is returned if no slave connection
is available and $fallbackToMaster
is false.
getTableSchema()
Obtains the schema information for the named table.
public
getTableSchema(string $name[, bool $refresh = false ]) : TableSchema|null
Parameters
- $name : string
-
table name.
- $refresh : bool = false
-
whether to reload the table schema even if it is found in the cache.
Return values
TableSchema|null —table schema information. Null if the named table does not exist.
getTransaction()
Returns the currently active transaction.
public
getTransaction() : Transaction|null
Return values
Transaction|null —the currently active transaction. Null if no active transaction.
hasEventHandlers()
Returns a value indicating whether there is any handler attached to the named event.
public
hasEventHandlers(string $name) : bool
Parameters
- $name : string
-
the event name
Return values
bool —whether there is any handler attached to the event.
hasMethod()
Returns a value indicating whether a method is defined.
public
hasMethod(string $name[, bool $checkBehaviors = true ]) : bool
A method is defined if:
- the class has a method with the specified name
- an attached behavior has a method with the given name (when
$checkBehaviors
is true).
Parameters
- $name : string
-
the property name
- $checkBehaviors : bool = true
-
whether to treat behaviors' methods as methods of this component
Return values
bool —whether the method is defined
hasProperty()
Returns a value indicating whether a property is defined for this component.
public
hasProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool
A property is defined if:
- the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a property of the given name (when
$checkBehaviors
is true).
Parameters
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
- $checkBehaviors : bool = true
-
whether to treat behaviors' properties as properties of this component
Tags
Return values
bool —whether the property is defined
init()
Initializes the object.
public
init() : mixed
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
noCache()
Disables query cache temporarily.
public
noCache(callable $callable) : mixed
Queries performed within the callable will not use query cache at all. For example,
$db->cache(function (Connection $db) {
// ... queries that use query cache ...
return $db->noCache(function (Connection $db) {
// this query will not use query cache
return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
});
});
Parameters
- $callable : callable
-
a PHP callable that contains DB queries which should not use query cache. The signature of the callable is
function (Connection $db)
.
Tags
Return values
mixed —the return result of the callable
off()
Detaches an existing event handler from this component.
public
off(string $name[, callable|null $handler = null ]) : bool
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.
Parameters
- $name : string
-
event name
- $handler : callable|null = null
-
the event handler to be removed. If it is null, all handlers attached to the named event will be removed.
Tags
Return values
bool —if a handler is found and detached
on()
Attaches an event handler to an event.
public
on(string $name, callable $handler[, mixed $data = null ][, bool $append = true ]) : mixed
The event handler must be a valid PHP callback. The following are some examples:
function ($event) { ... } // anonymous function
[$object, 'handleClick'] // $object->handleClick()
['Page', 'handleClick'] // Page::handleClick()
'handleClick' // global function handleClick()
The event handler must be defined with the following signature,
function ($event)
where $event
is an [[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.');
});
Parameters
- $name : string
-
the event name
- $handler : callable
-
the event handler
- $data : mixed = null
-
the 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 [[Event::data]].
- $append : bool = true
-
whether 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.
Tags
open()
Establishes a DB connection.
public
open() : mixed
It does nothing if a DB connection has already been established.
Tags
quoteColumnName()
Quotes a column name for use in a query.
public
quoteColumnName(string $name) : string
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.
Parameters
- $name : string
-
column name
Return values
string —the properly quoted column name
quoteSql()
Processes a SQL statement by quoting table and column names that are enclosed within double brackets.
public
quoteSql(string $sql) : string
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]].
Parameters
- $sql : string
-
the SQL to be quoted
Return values
string —the quoted SQL
quoteTableName()
Quotes a table name for use in a query.
public
quoteTableName(string $name) : string
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.
Parameters
- $name : string
-
table name
Return values
string —the properly quoted table name
quoteValue()
Quotes a string value for use in a query.
public
quoteValue(string $value) : string
Note that if the parameter is not a string, it will be returned without change.
Parameters
- $value : string
-
string to be quoted
Tags
Return values
string —the properly quoted string
setDriverName()
Changes the current driver name.
public
setDriverName(string $driverName) : mixed
Parameters
- $driverName : string
-
name of the DB driver
setQueryBuilder()
Can be used to set [[QueryBuilder]] configuration via Connection configuration array.
public
setQueryBuilder(array<string|int, mixed> $value) : mixed
Parameters
- $value : array<string|int, mixed>
-
the [[QueryBuilder]] properties to be configured.
Tags
transaction()
Executes callback provided in a transaction.
public
transaction(callable $callback[, string|null $isolationLevel = null ]) : mixed
Parameters
- $callback : callable
-
a valid PHP callback that performs the job. Accepts connection instance as parameter.
- $isolationLevel : string|null = null
-
The isolation level to use for this transaction. See [[Transaction::begin()]] for details.
Tags
Return values
mixed —result of callback function
trigger()
Triggers an event.
public
trigger(string $name[, Event|null $event = null ]) : mixed
This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.
Parameters
- $name : string
-
the event name
- $event : Event|null = null
-
the event instance. If not set, a default [[Event]] object will be created.
useMaster()
Executes the provided callback by using the master connection.
public
useMaster(callable $callback) : mixed
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();
});
Parameters
- $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.
Tags
Return values
mixed —the return value of the callback
createPdoInstance()
Creates the PDO instance.
protected
createPdoInstance() : PDO
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.
Return values
PDO —the pdo instance
initConnection()
Initializes the DB connection.
protected
initConnection() : mixed
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.
openFromPool()
Opens the connection to a server in the pool.
protected
openFromPool(array<string|int, mixed> $pool, array<string|int, mixed> $sharedConfig) : Connection|null
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]].
Parameters
- $pool : array<string|int, mixed>
-
the list of connection configurations in the server pool
- $sharedConfig : array<string|int, mixed>
-
the configuration common to those given in
$pool
.
Tags
Return values
Connection|null —the opened DB connection, or null
if no server is available
openFromPoolSequentially()
Opens the connection to a server in the pool.
protected
openFromPoolSequentially(array<string|int, mixed> $pool, array<string|int, mixed> $sharedConfig) : Connection|null
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.
Parameters
- $pool : array<string|int, mixed>
-
the list of connection configurations in the server pool
- $sharedConfig : array<string|int, mixed>
-
the configuration common to those given in
$pool
.
Tags
Return values
Connection|null —the opened DB connection, or null
if no server is available
attachBehaviorInternal()
Attaches a behavior to this component.
private
attachBehaviorInternal(string|int $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior
Parameters
- $name : string|int
-
the name of the behavior. If this is an integer, it means the behavior is an anonymous one. Otherwise, the behavior is a named one and any existing behavior with the same name will be detached first.
- $behavior : string|array<string|int, mixed>|Behavior
-
the behavior to be attached
Return values
Behavior —the attached behavior.
restoreQueryBuilderConfiguration()
Restores custom QueryBuilder configuration after the connection close/open cycle
private
restoreQueryBuilderConfiguration() : mixed
rollbackTransactionOnLevel()
Rolls back given [[Transaction]] object if it's still active and level match.
private
rollbackTransactionOnLevel(Transaction $transaction, int $level) : mixed
In some cases rollback can fail, so this method is fail safe. Exception thrown from rollback will be caught and just logged with [[\Yii::error()]].
Parameters
- $transaction : Transaction
-
Transaction object given from [[beginTransaction()]].
- $level : int
-
Transaction level just after [[beginTransaction()]] call.