We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to globally change database connection?

I set up 2 connections in config. I know I can change the default in MyModel::initialize() method and use $this->setConnectionService(connectionName);

but what if I want to globally change this? App started, and suddenly I have to change another connection. How to re-initialize all the models? Or should I have to write a manually db changer method? To all model? Thats not conviement if I have 200 models and it just groves



51.2k

Why and when you need to switch to another connection ? You can use this https://docs.phalcon.io/en/latest/reference/models.html#setting-multiple-databases and you can create a base model, and all the other models will extend the base one. Eg:

class BaseModel extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        // do whatever you want
    }
}

class UserModel extends BaseModel
{
    public function initialize()
    {
        // do whatever you want, but call the parent method

        parent::initialize();
    }
}