Dynamic Global Variable For All Views And Controllers


Quite new to the whole Yii process and created a small application.

In all URLs i will have a companyid passed in.

i.e. domain/index.php/revenue/15

So 15 is the id of the company.

revenue is the controllers.

This is set up in config in urlmanager so that in the revenue controller I can access the companyid = 15:

I have a company model that gets out all the company details that I want to be able to access in all views.


class RevenueController extends Controller {

public function actionIndex($companyId)



	//var_dump($leagueAndTables); die();







However as every view and action within this controller (and others) will need this data I do not want to have to load it in every action and pass it into every view. I just want to get the data once for the request and have it available for the whole request to use in any model.

I have tried adding it into an init function both within the company controller and the controller that is extended by it. Was thinking of adding it into Yii App data like:



But when I do this the init function does not seem to have access to companyId in either controller.

So firstly is Yii::app()->params a good place to put the data so that I can then access it in my all my views.

Secondly, why can I not access the companyId parameter when I can do in the main actions of the controllers.

And Thirdly - am I completely on the wrong track and if so which track should I try to get onto before I get run over?



There are a few options, but the easiest to implement might be lazy-loading the company the first time it’s required. You should be able to get the company ID using


You could do something like the following in your base controller:

private $_currentCompany = null;

public function getCurrentCompany()


    if ($this->_currentCompany === null)


        $companyId = Yii::app()->request->getQuery('companyId');

        $this->_currentCompany = Company::model()->findByPk($companyId);


    return $this->_currentCompany;


At least this way you only access the database if the current action needs to, rather than on every request.

If the method returns null, then the record wasn’t found, which suggests an invalid company ID, or that the company ID wasn’t specified in the URL for the current action.

Thanks for your help. Seems to be working.

I have put Yii::app()->params[‘company’] = $this->getCurrentCompany(); into init of the main controller. And now I can access this in my views. So thanks muchly.