1

This is my code:

for ($i=0; $i < count($rights); $i++) {
    $this->setState($rights[$i], true);
}

Here I am setting the setState dynamically, but I want to get all of states in a list. I did not find any references about this. I only found this:

Yii::app()->user->getState('name');

But this is not helping me. How can I get a list of all states in yii? thx

Jozsef Naghi
  • 1,085
  • 3
  • 14
  • 32
  • Did you take look at [this](http://www.yiiframework.com/forum/index.php/topic/56477-get-user-states/). I think it's the only way to get all state but you will also get useless information. – LolWalid May 05 '15 at 09:01

2 Answers2

1

According to the API of CWebUser, there's no function for that purpose.

According to the code of setState, you can see that it saves the values in a session and that there's no another way of "storing" the used states. (Like an array of all created states)

public function setState($key,$value,$defaultValue=null)
{
    $key=$this->getStateKeyPrefix().$key;
    if($value===$defaultValue)
        unset($_SESSION[$key]);
    else
        $_SESSION[$key]=$value;
}

One solution is manually going through all the existing sessions ($_SESSION) but in my opinion it's not very efficient idea.

Another solution is to have a property/variable (array) to hold all the states that you've created and than using a foreach loop, use getState.

Ofir Baruch
  • 10,323
  • 2
  • 26
  • 39
0

If you look at the CWebUser source code, then you will see that getState() function just looking for a $_SESSION key with stateKeyPrefix

public function getState($key,$defaultValue=null)
    {
        $key=$this->getStateKeyPrefix().$key;
        return isset($_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
    }

You can get the state prefix and all states with following code:

$prefix = Yii::app()->user->stateKeyPrefix;
$states = array();
foreach( $_SESSION as $key=>$value ) {
  if( strpos($key, $prefix) === 0 ) {
    states[ substr( $key, strlen( $prefix ) ) ] = $value;
  }
}
Bfcm
  • 2,686
  • 2
  • 27
  • 34