[solved] how to display user data

Hi guys,

on each of my pages i have a header displaying some User->profile informations. I am using a portlet to display them.




//in my portlet:

    protected function renderContent()

    {

		$user = User::model()->findbyPk(Yii::app()->user->id);

        $this->render('userHeader', array('user'=>$user));

    }



In most of my controllers, i need the User->profile data for checks and calculations.

So i am querying in fact the user->profile data two times on each page from the database,

which is not my desired solution :)

Can anyone give me a hint how to get a AR Model Instance as a quasi ‘global’, so i can use it in my controller and the portlet?

TIA

Marco

You can save some user data in session using setState() method when user logs in.

You can also create a new method in the User class called “getUser”, for example. This method will retrieve a user from a database and store it in a static field, so next time a query won’t be performed again.

It’s a bit too much data for the session, but i will try using your second tip.

Thanks,

Marco

hmm,

how resp. where can i store the data in a ‘static’ variable? If it is an object variable, i have the same problem as before. I simply don’t know how i use the same object instance of User in my controller and the portlet.

Can i access controller variables from my portlet?

Marco

In both, controller and portlet, user id is the same. So you can do the following:




class User extends CActiveRecord

{

    private static $user;


    // ...


    public function loadUser()

    {

        if (self::$user instanceof User)

            return self::$user;


        return self::$user = User::model()->findbyPk(Yii::app()->user->id);

    }

}



In this case, when you’ll call this method




$user = User::model()->loadUser();



second time, a previously retrieved model will be simply returned.

You can make this method static, I just wanted it to look like others "find" methods.

If you don’t like this approach, you can add a new public property “user” to your controller. Assign a value in action and then use the following code in portlet:




$this->owner->user;



The static variable works perfect for me.

Thank you again for your help!

Marco