A Question About The Wiki Article "a Multi-Tenant Strategy Using Yii And Mysql"

Hi, in the great article "A Multi-Tenant Strategy using Yii and MySQL" I found something that do not understand.

Why on every request you need to execute the beginRequest method in AppStartup class? Could not be better to do that only once after the user login?

Thanks

n.b.: I can’t post comments under the article because I’m new user.

The reason is Yii’s design; refer to the Application Life Cycle in the Guide. For every request the app is initialized first from the config file, thus resetting the db connection. The only thing that’s persisted from one request to the next is the PHP session so that’s why one can access Yii::app()->user->id to retrieve the tenant credentials.

A different approach that I haven’t tried is doing it in the init() method of the Controller.php class from where all other controllers extend.

Good eye Luciano, this particular issue took me a few weeks to figure out. I updated the wiki to explain it, thanks… :)

Thanks for reply Josè.

If I understand the aim of beginRequest() function is to restore the connection, ok!

It wouldn’t be more performant to store the username and password in session variables instead of doing on every request the following time consuming instructions?

$u = TUser::model()->findByPk(Yii::app()->user->id);

$tu = TTenant::model()->findByPk($u->tenant_id)->dbu;

$tp = TTenant::model()->findByPk($u->tenant_id)->e_dbpwd;

Sure, you can store the db username and password in the session, but it’s a security risk. You’re right that executing 3 db accesses imposes a theoretical performance hit; the above code can be improved by 33% just doing this:




$u = TUser::model()->findByPk(Yii::app()->user->id);

$t = TTenant::model()->findByPk($u->tenant_id);

$tu = $t->dbu;

$tp = $t->e_dbpwd;



Better yet, a 66% improvement is to store the tenant_id as a user session variable "tid" in WebUser.php and use it as follows:




$t = TTenant::model()->findByPk(Yii::app()->user->tid);

$tu = $t->dbu;

$tp = $t->e_dbpwd;



These optimizations do not expose the db user/password to the session and are therefore safer. In any case, I haven’t had performance issues with my app so far; if and when I do (hopefully soon because of growth!) then I’ll use the above.

Thanks for your input and have a Happy New Year!

Thank you Josè and wish you an happy new year!