Search code examples
yiiclass-visibilityglobal-scope

yii - variable available to each controller


I am new to yii.

I am using more than 1 controller in my website and each controller has few actions.

I want to use some variables across each controller (Value of variable will be fixed, I need some constants for a formula). Whats the best place (standard way) to define those variables ? Should I use session ? (as value is not going to change).


Solution

  • Not sure what you are using your vars for, but you can do it by defining them in your config main.php

    'params'=>array(
    'someVar1'=>'varValue1',
        'someVar2' => 'varValue2',
    ),
    

    Then you can access them in ANYWHERE by calling

    Yii::app()->params['someVar1']
    

    They will be available anywhere in your application.

    Or you can extend all your controllers off of a base class and define your constants there

    Base Controller:

    class Controller extends CController { 
    
        const SOME_VAR = 'someValue'; 
    }
    

    Your controller:

    class YourController1 extends Controller
    {
        public function actionIndex()
        {
            echo parent::SOME_VAR;
        }
    
    }
    

    Your other controller:

    class YourController2 extends Controller
    {
        public function actionLogin()
        {
             echo parent::SOME_VAR;
        }
    
     }