Skip to content

Using Connection Manager

Yo-An Lin edited this page May 16, 2017 · 7 revisions

The ConnectionManager could be used to connect to the instances defined in the config. The db commands use ConnectionManager to manage the databases.

DataSourceManager inherits ConnectionManager to provide the database connection methods like getMasterConnection()

To create the connection manager for the instances, simple construct the connection manager with $config->getInstances()

use Maghead\Manager\ConnectionManager;

$conns = new ConnectionManager($config->getInstances());

To connect to an instance:

$conn = $conns->connectInstance('local'); // This returns Maghead\Runtime\Connection

To get the global data source manager object:

use Maghead\Manager\DataSourceManager;

$dsm = DataSourceManager::getInstance();

Before getting the global data source manager object to use, be sure to setup the environment via Bootstrap::setup.

The code below could be used to create the data source manager separately:

use Maghead\Manager\DataSourceManager;

$dsm = new DataSourceManager($config->getDataSources());

To connect to the database:

$conn = $dsm->getConnection('master'); // Maghead\Runtime\Connection
$node1 = $dsm->getConnection('node1'); // Maghead\Runtime\Connection

$conn = $dsm->getMasterConnection(); // Maghead\Runtime\Connection

You may now operate your SQL query with the returned connection as usual:

foreach($conn->query('SELECT * from FOO') as $row) {
    print_r($row);
}

Clone this wiki locally