Persistent storage for WebUser

Hi,

I noticed that the informations in WebUser class were not persistent from one webpage to the other, so I upgraded the class using the State variables:




class EWebUser extends CWebUser{

 

    function getLevel(){

        if($this->hasState('userLevel') == 0)   

        {

            $user = $this->loadUser();

            if($user !== null)

                $this->setState('userLevel',$user->getLevel());

            else

                return 1;

        }

        return $this->getState('userLevel');                  

    }

  

    // Load user model.

    protected function loadUser()

    {

        if ( $this->hasState('user') == 0 ) {

            $this->setState('user',User::model()->with('scoreT','scoreD')->findByPk($this->id));

        }

        return $this->getState('user');

    }

}



Does anyone see any problem that could come from my solution? Why is it not implemented this way by default?

Thanks for any comment & help.

I prefer to not store CActiveRecords as serialized objects (state) because they are meant represent a row in the database, if you are reading it out of state and it has changed in the database, then you are making false assumptions.

There isn’t anything wrong with what you have implemented if it works for you, if the job needs a hammer, use a hammer.

However, every application is different and not everyone wants to store every property in WebUser in state. My WebUser implementation looks different in almost every application I build.

Hi Luke,

Thanks for sharing your opinion on the matter. I understand the problem you mention, yes you’re right it could be a problem in some circumstances.

In my case I need to use the function getLevel() to determine the Theme to use for every page, that’s why I cannot afford to have the same query done for each page. Here is how I extended the main Controller class:




class MyController extends Controller

{ 

    public function render($view,$data=null,$return=false)	{		

        switch(Yii::app()->user->getLevel())

        {			

            case 1:				

                    Yii::app()->setTheme('theme1');			

                break;			

            case 2:				

                    Yii::app()->setTheme('theme2');			

                break;			

            case 3:				

                    Yii::app()->setTheme('theme3');			

                break;		            

        }		

        return parent::render($view,$data,$return);	               

    }

}



Suggestions or comments are welcome.