Yii provides ORM based development which is OK for normal development. My question is, in my application there are many user related data like user info, user settings, user preferences and so on. Here user means the current logged in user.
If somewhere I need the background picture setting of the User I do the following
$user = User::model()->findByPk(Yii::app()->user->id);
$bgImage = $user->settings->backgroundImage;
I repeat the same thing on another places of the application wherever I need background image. Means again create instance of the $user which I don't think a good approach. So, is there a way by which we don't need to instantiate the user class again and again??? Remember I don't like the session approach.
Another approach is to use a singleton. In library code, do this:
public static function getUser() {
static $user;
if (!$user) {
$user = User::model()->findByPk(Yii::app()->user->id);
}
return $user;
}
This can be called as many times as you like, but in a single web request the database call will be made only once.
Note that if Yii::app()->user->id
might change inside a web request, it's worth having a static array indexed by that value instead - so the method caches correctly if your user logs on or off.