I have read the tutorials on how to make a sub class of CWebUser and followed the instructions. The paths all work, and the code is getting into the right methods, however the value returned from my getter is always nil.
class PersonUser extends CWebUser {
// Store model to not repeat query.
private $_person;
// Load user model.
public function loadPerson($id=null, $duration=0)
{
$this->login($id,$duration);
$this->_person=Person::model()->findByPk(Yii::app()->user->id);
}
public function getPerson()
{
return $this->_person;
//return Person::model()->findByPk($this->id);
}
}
If I echo in the loadPerson method $this->_person->first_name
after I set _person
I get the value I expect. However, at any later time, if I ask for Yii::app()->user->person
, the getPerson()
method gets called, but $this->_person
is now null. I know it's getting in there, if I uncomment the line below and have it look up the person every time, it works.
Is this an issue with Yii? I would really like to be able to cache the person object so I can reference it throughout the session without having to make more calls to the database. What am I missing??
There is no issue with Yii.... As per the documentation, CWebUser class identifies predefined variables "id" and "name" which remains persistent through out the session. Any additional variables should be used with getState() and setState() methods. " Moreover CWebUser should be used together with IUserIdentity Class which implements the actual authentication algorithm. "
The method loadUser()
is never called. And the login()
call inside also doesn't make sense. A simpler implementation of getPerson()
would be.
private $_person = false;
public function getPerson()
{
if($this->_person===false)
$this->_person = Person::model()->findByPk($this->id);
return $this->_person;
}