Yii registry, how to use it, is it exists at all?

You are viewing revision #7 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#8) »

  1. Introduction
  2. Registry in Yii
  3. CMap
  4. Tip 1
  5. Tip 2
  6. Links

Introduction

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

Zend_Registry::get('paramName');
Zend_Registry::set('paramName');

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:

Yii::app()->getParams()

it is the same like use

Yii::app()->params

Smart to use with CVarDumper:

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

If You use CVarDumper, it looks like this:

CAttributeCollection#1
(
    [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

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

CMap

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

Yii::app()->params->keys;

Will return array like this:

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

I mentioned the unset before, but you also can use

Yii::app()->params->remove('abc');

You can delete all params via

Yii::app()->params->clear();

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

params.php

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

__DIR__

, replace it with

dirname(__FILE__)

And the config/params.php contains:

<?php
return array(
	'abc' =>123,
);

Links

Russian version