Different db connections for guest and authenticated users

Is it possible to use different db connection component for a guest user vs authenticated user.

I am trying to implement an app in which all users info (and some other info) is stored in a unique database (generalDb). When the user is authenticated, the user id from the ‘user’ table in generalDb is used to obtain the mapping for the specific db related to the user. All the user-related dbs are of the same structure…

Just setup your two dbs in the config file and if you use a lot of Active Records extend CAtiveRecord to implement a custom getDbConnection() that selects the DB based on user status. If you use query builder of SQL then you will require more logic.

If you need a distinct database connection for each user, extend CWebApplication:

class MyWebApplication extends CWebApplication


  private $_userDb;

  public function getUserDb()


	if ( ! isset($this->_userDb)) {

  	$this->_userDb = Yii::createComponent(array(

      	'class' => 'CDbConnection',

      	// get configuration data for user's db connection from anywhere you store it



	return $this->_userDb;



You can then access user’s db connection as Yii:.app()->userDb anywhere in your application.

Thanks for your replies. I suppose the solution provided by phtamas would be more appropriate for my usage. I suppose the class file would go into components folder?

Is there also a way of creating an event which can do this and setting the event to occur immediately after the app begins to run?

That’s probably the most appropriate choice. But wherever you place it, it needs to be included before instantiation :

require 'path/to/MyWebApplication.php';

$app = Yii::createApplication('MyWebApplication', $config);

A behavior that listens to onBeginRequest event can be attached to CWebApplication but it seems to be a bit overcomplicated to me.