Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Question about DB connections

If I was to redefine the db connection as below, would that leave the original connection open or close it ? I am trying to switch between databases, the host could also change ie. master/slave

    DI::getDefault()->set('db', function ()
        use ($db_host, $db_username, $db_password,$db_name)
    {
        $connection["host"] = $db_host;
        $connection["username"] = $db_username;
        $connection["password"] = $db_password;
        $connection["dbname"] = $db_name;
        return new DbAdapter($connection);
    });

    DI::getDefault()->set('db', function ()
        use ($db_host, $db_username, $db_password,$db_name2)
    {
        $connection["host"] = $db_host;
        $connection["username"] = $db_username;
        $connection["password"] = $db_password;
        $connection["dbname"] = $db_name2;
        return new DbAdapter($connection);
    });
edited Jul '16

You could perhaps extend DbAdapter class with connect() method override which will make switch between db1 and db2.

So you would call the switch as:

$this->db->connect(1); //connect to DB 1

$this->db->connect(2); //DB 2
public boolean connect ([array $descriptor]) inherited from Phalcon\Db\Adapter\Pdo
This method is automatically called in Phalcon\Db\Adapter\Pdo constructor. Call it when you need to restore a database connection


38.6k
Accepted
answer
edited Jul '16

https://github.com/phalcon/cphalcon/blob/cf3c1fe62184d36d24c543c0b4f9993ea8f2445b/phalcon/di.zep#L122

First instance will be replaced by the new one in an array. From here standard PHP logic applies (db persistency, garbage collection, referencing variables), so it depends on a few things whether the connection will actually be closed.

If you want to be sure, call disconnect, for eg by implementing a custom adapter as @stamster suggested