Yii registry, how to use it, does it exist at all?

  1. Introduction
  2. Registry in Yii
  3. CMap
  4. Tip 1
  5. Tip 2
  6. Addition 1: Yii global state
  7. Links


From time to time people ask about registry...

If you coming to Yii with experience with Zend Framework for example, most likely you get used to


Registry in Yii

In Yii you also has it

set variable:

Yii::app()->params['abc'] = 123;

get variable:

echo Yii::app()->params['abc'];

get all defined variables:


it is the same like use


Smart to use with CVarDumper:

CVarDumper::dump(Yii::app()->getParams(), 10, true);

If You use CVarDumper, it looks like this:

    [caseSensitive] => true
    [CMap:_d] => array
        'abc' => 123
        'a' => 123
        'c' => 1316855672
        'd' => 'cookie'
    [CMap:_r] => false
    [CComponent:_e] => null
    [CComponent:_m] => null

You can also do mass assignment via array

Yii::app()->setParams(array('a' => 123, 'c' => time(), 'd' => 'cookie'));

To unset some key, you can use



Because the params is CMap instance

You can use the Cmap methods

for example:

get total of variables defined:

echo Yii::app()->params->getCount();

for the example above will return 4

It is the same like

Yii::app()->params->count; or Yii::app()->params->count();

You can get the keys


Will return array like this:

'0' => 'abc'
    '1' => 'a'
    '2' => 'c'
    '3' => 'd'

I mentioned the unset before, but you also can use


You can delete all params via


Tip 1

->params is the same like ->getParams() method params['sdf']=$val is the same like calling setParams('sdf',$val); This is right to all the framework, magic method take care all the "magic" behind it Just add for example in Controller that extends CController getSomething and you can use $this->something ...

Tip 2

For most of you this is trivial, but: The initial params don't come from nowhere In configs/main.php You have the params array

'params'=>array('abc' => 123),

I personally like to add in config folder


And than you can replace the above line with:

For php > 5.3

'params'=>require( __DIR__ .'/params.php'),

for < 5.3 you should't use


, replace it with


And the config/params.php contains:

return array(
	'abc' =>123,

Addition 1: Yii global state

The params array, can be good registry for the current life cycle. but yii also has something called "globalstate", it allow you save the data "forever"

CApplication has 3 methods:
getGlobalState(string $key, mixed $defaultValue=NULL)
setGlobalState(string $key, mixed $value, mixed $defaultValue=NULL)

every thing you set via setGlobalState will be saved in runtime/global.bin in serialized form

Some common component that use it is CSecurityManager for validation key

And be careful with clearGlobalState, because it will regenerate the security key... it may have very bad effect if you for example encrypted passwords for user without specify your own key


Russian version