PrimaryReplicaTrait

Type
Trait
Namespace
craft\db
Implemented by
craft\db\Connection
Since
3.4.25

View source

# Public Methods

Method Description
getPrimary() Returns the currently active primary connection.
getPrimaryPdo() Returns the PDO instance for the currently active primary connection.
getReplica() Returns the currently active replica connection.
getReplicaPdo() Returns the PDO instance for the currently active replica connection.
usePrimary() Executes the provided callback by using the primary connection.

# getPrimary()

Returns the currently active primary connection.

If this method is called for the first time, it will try to open a primary connection.

View source

Returns

craft\db\Connection, null – The currently active primary connection. null is returned if no primary connection is available.

# getPrimaryPdo()

Returns the PDO instance for the currently active primary connection.

This method will open the primary DB connection and then return \craft\db\pdo.

View source

Returns

PDO – The PDO instance for the currently active primary connection.

# getReplica()

Returns the currently active replica connection.

If this method is called for the first time, it will try to open a replica connection when \craft\db\enableReplicas is true.

View source

Arguments

  • $fallbackToPrimary (boolean) – Whether to return the primary connection if no replica connections are available.

Returns

craft\db\Connection, null – The currently active replica connection. null is returned if no replica connections are available and $fallbackToPrimary is false.

# getReplicaPdo()

Returns the PDO instance for the currently active replica connection.

When \craft\db\enableReplicas is true, one of the replicas will be used for read queries, and its PDO instance will be returned by this method.

View source

Arguments

  • $fallbackToPrimary (boolean) – Whether to return the primary PDO if no replica connections are available.

Returns

PDO, null – The PDO instance for the currently active replica connection. null is returned if no replica connections are available and $fallbackToPrimary is false.

# usePrimary()

Executes the provided callback by using the primary connection.

This method is provided so that you can temporarily force using the primary connection to perform DB operations even if they are read queries. For example,

$result = $db->usePrimary(function ($db) {
    return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
});

View source

Arguments

  • $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.

Returns

mixed – The return value of the callback

Throws

  • Throwable
    if there is any exception thrown from the callback