have a variable available in all Yii views

inheritance, php, scope, yii

Solution

Create class field in your base controller class:

class Controller extends CController { 
    public $user_profile;

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

Don't need to pass it directly to view:

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

Then you can access it in view using `$this`:

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

Problem

I would like to have a variable $user_profile available in most of my view files, without me having to create the variable in each controller file. At the moment I have things working but I was wondering if there is a better solution I have some code to populate a variable ``` $user_profile = YumUser::model()->findByPk(Yii::app()->user->id)->profile; ``` Then a parent class ``` class Controller extends CController { public function getUserProfile() { $user_profile = YumUser::model()->findByPk(Yii::app()->user->id)->profile; } } ``` Then I have all 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 simply access the $user_profile variable.

Original source