Change Database Name on Init

Upon initialization, I would like to set the database name of a connection, based on a session variable.

I see there’s a behavior for EVENT_AFTER_OPEN, but wondering if there’s a way to set the database before Opening.

Any help would be GREATLY appreciated.

Hi Can you check if this is the one you need?




$connection=new CDbConnection($dsn,$username,$password);



For more details Click here.

Thanks, but I don’t think that is what I need.

I have a DB setup in config, and I have models configured based on that connection. The models use the getDb() override to reference the database connection, e.g. db2.

What I would like is a simple, elegant way to change the database name before that db2 connection is opened. I see that I can setup a Behavior to execute AFTER the database is opened, but I’d like to find one that executes before, where I can change the database name.

OK… I don’t know if this is the best way, but here’s what I did…

In each Model, I added the function:

public static function getDb()

{

    return Helpers::getMyDb();

}

I then created a Helpers function:

public function getMyDb()


{


    $session = Yii::$app->session;


    if(isset($session['myDb']))


        $myDb = $session['myDb'];


    else


        $myDb = 'test';


    


    $dsn = Yii::$app->get('db');


    $dsn->dsn = 'mysql:host=localhost;dbname=' . $myDb;


    return $dsn;


}

Is this right? Does anyone know of a better way?

Thanks