I would like to know whether it is possible or if there is a easier way to do this.
On many pages i'd like to use the relational data, now every page i use it i place the following code:
<?php
if(!Yii::app()->user->isGuest){
$user = User::model()->findByPk(Yii::app()->user->id);
}
?>
So I can use the following in the view:
$user->account->name
To display current users related account's name
It would be nice if I could just do the following:
Yii::app->user->account->name
Set state isn't what i'm looking for since it's not only the account name i want to use, and I don't want to add a state for all relational data I might want to use.
Solution
|
|
|
V
Solution
I combined the good of both answers to create the following:
class WebUser extends CWebUser {
private $_user;
public function getAccount(){
if(!$this->isGuest && (!isset($this->_user) || Yii::app()->user->id != $this->_user->id)){
$this->_user = User::model()->findByPk(Yii::app()->user->id);
}
if(!empty($this->_user)){
return $this->_user->account;
} else {
return false;
}
}
}
So now I can use the following:
Yii::app()->user->account->name
The above method retrieves the data if the user is logged in and there is no data stored or the user has a different id.
Place it in Components and be sure to add the part Afnan talks about to the config (main.php)
I accept the answer of Afnan because it helped me most (The part I needed to know)