There is a variable available in all views of Yii

I would like to have the $ user_profile variable available in most of my view files, without having to create a variable in every controller file. Everything works for me at the moment, but I was wondering if there is a better solution

I have code to populate a variable

$user_profile = YumUser::model()->findByPk(Yii::app()->user->id)->profile; 

Then parent class

 class Controller extends CController { public function getUserProfile() { $user_profile = YumUser::model()->findByPk(Yii::app()->user->id)->profile; } } 

Then I have all the other controllers inheriting the Controller class, for example

 class DashboardController extends Controller { public function actionIndex() { $user_profile = parent::getUserProfile(); $this->render('index', array('user_profile' => $user_profile)); } } 

Then, finally, in the view file, I can just access the $ user_profile variable.

+4
source share
3 answers

Create a class field in the controller base class:

 class Controller extends CController { public $user_profile; public function init() { parent::init(); $this->user_profile = YumUser::model()->findByPk(Yii::app()->user->id)->profile; } } 

No need to pass it directly to view:

 public function actionIndex() { $this->render('index'); } 

Then you can access it with $this :

 // index.php var_dump($this->user_profile); 
+8
source

You already have getter defined, so you can use $this->userProfile from both your controllers and your views. I would add only caching logic to avoid multiple database queries:

 class Controller extends CController { protected $_userProfile=false; /* * @return mixed a User object or null if user not found or guest user */ public function getUserProfile() { if($this->_userProfile===false) { $user = YumUser::model()->findByPk(Yii::app()->user->id); $this->_userProfile = $user===null ? null : $user->profile; } return $this->_userProfile; } 
+2
source

For user profile information, I populate a small number of variables at login, using setState to store data.

In your UserIdentity class, after successful authentication, you can save data like this:

 $userRecord = User::model()->find("user_name='".$this->username."'"); $this->setState('display_name', (isset($userRecord->first_name)) ? $userRecord->first_name : $userRecord->user_name); 

Then, in any view, you can access, for example:

 echo (isset(Yii::app()->user->display_name) ? Yii::app()->user->display_name : 'Guest'); 
0
source

Source: https://habr.com/ru/post/1491081/


All Articles