Dynamic tableprefix for multi tenant application

I want to build a multi tenant application. One application will serve multiple companies (tenants) each with many users.

I want to use this structure to enable multi tenancy:

  • A user will login on tenantname.application.com. The application will fetch the tenant’s name from the url and authenticate the user.

  • The tenants unique table prefix will be stored in a session using CWebUser.

  • The application will access the database by using the table prefix from the session.

How can I set the CDbConnection’s tableprefix from the sessiondata?

Try:


// authenticate method in CUserIdentity

$this->setState('prefix', 'prefix_');

...


// Model

public function tableName()

{

	return Yii::app()->user->getState('prefix') . 'tablename';

}

Tnx. That will work, but I rather use a method such that I don’t have to add prefix code to every model. I was thinking about using the CDbConnection’s tablePrefix property, but I don’t know how to set that property otherwise than configuring it in the configuration file.

Did you try something like


Yii::app()->db->tablePrefix = Yii::app()->user->getState('prefix');

in your authenticate method after authenticating?

Thank you all for your help. I will post my solution, so others facing the same problem find a solution here.

I created a component DbConnection which overrides the constructor of CDbConnection. When the DbConnection is created for the first time during a session, it will look up the table prefix in the database using the subdomain and store it in the session data. Each time a DbConnection is created it will set it’s own tablePrefix property.