Dynamic database parameters

(Using Yii 2.0.46) I have 2 database components, dbix and db. dbix does not change as it is used to login the user, but I want to vary the parameters of db depending on the user. I want to use Yii::$app->db etc. in my project. I can close() the connection, reassign to Yii::$app->db->dsn etc, then open() the connection with the new settings. But on the next page refresh it reverts to the settings in config[‘db’]. I am nearly there, but can anyone please help me to figure this out? Do I need to somehow override the settings in $config[‘db’]?

In models can define like that:

    public static function getDb()
    {
        if (\Yii::$app->user->id < 1000) {
            return \Yii::$app->db1;
        }
        return \Yii::$app->db2;
    }

Thank you. Yes that works, probably as \Yii::$app->db$n, but I would have to assign components db1, db2, db3…dbn in $config. What I was hoping for is a group record for each type of user with fields dsn, dbuser, dbpwd, etc from which I could generate a db component. But if your suggestion is the only way, it would work. Thanks for your reply.

Second solution is extend db connection component from yii\db\Connection and in constructor add logic for set dsn, username and password.

2 Likes

Should this no longer be “static” method?

Replying to my own post, I have found a solution which seems to work, by editing the entry script index.php. But I am not an expert and this takes me beyond my comfort zone. Please advise me if you see any unintended consequences or blunders…

//(new yii\web\Application($config))->run();

//Replace with this code:

$application = new yii\web\Application($config);

if (!Yii::$app->user->isGuest) {   //bypassed when user logged in
    //When user is logged in, get db params from user's group table. 
    //Put db params in config array, in session, and access it here
    $dbconfig = Yii::$app->session->get('dbconfig');
    //Add db component to main $config array
    $config['components']['db'] = $dbconfig;
    //Create application object again
    $application = new yii\web\Application($config);
}

$application->run();

Thank you for taking an interest.