ppsreejith
ppsreejith

Reputation: 3438

Sending more data to changeIdentity in CWebUser by overriding it?

Disclaimer: Complete beginner in Yii, Some experience in php.
In Yii, Is it OK to override the login method of CWebUser?
The reason i want to do this is because the comments in the source code stated that the changeIdentity method can be overridden by child classes but because i want to send more parameters to this method i was thinking of overriding the login method too (of CWebUser).
Also if that isn't such a good idea how do you send the extra parameters into the changeIdentity method.(By retrieving it from the $states argument somehow ??). The extra parameters are newly defined properties of UserIdentity class.

Upvotes: 0

Views: 484

Answers (1)

Willem Renzema
Willem Renzema

Reputation: 5187

It is better to first try to do what you wish to do by overriding components/UserIdentity.php's authenticate method. In fact, that is necessary to implement any security system more advanced than the default demo and admin logins it starts you with.

In that method, you can use

$this->setState('myVar', 5);

and then access that anywhere in the web app like so:

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

If myVar is not defined, that method will return null by default. Otherwise it will return whatever it was stored as, in my example, 5. These values are stored in the $_SESSION variable, so they persist as long as the session does.

UPDATE: Okay, took the time to learn how this whole mess works in Yii for another answer, so I'm sharing my findings here as well. The below is mostly copy pasted from a similar answer I just gave elsewhere. This is tested as working and persisting from page to page on my system.

You need to extend the CWebUser class to achieve the results you want.

class WebUser extends CWebUser{
    protected $_myVar = 'myvar_default';

    public function getMyVar(){
        $myVar = Yii::app()->user->getState('myVar');
        return (null!==$myVar)?$myVar:$this->_myVar;
    }

    public function setMyVar($value){
        Yii::app()->user->setState('myVar', $value);
    }
}

You can then assign and recall the myVar attribute by using Yii::app()->user->myVar.

Place the above class in components/WebUser.php, or anywhere that it will be loaded or autoloaded.

Change your config file to use your new WebUser class and you should be all set.

'components'=>
    'user'=>array(
        'class'=>'WebUser',
    ),
...
),

Upvotes: 1

Related Questions