Is it considered bad practice to use Yii::app()->user in models?

Hey everyone,

question already in the title. Is it considered bad practice to use CWebUser in models? Because I do it all the time in scopes, relations, and so on … Coming across the same issues described in the topics below (exception thrown when Yii::app()->user is called in console applications) I think, I might need to change my current way of handling session information in models.

Related problem:

Thank you for your feedback!

It is ok to use it in model…

I’m not surprises you cant use it in Console …

Can you provide some example, how and why you’re using user (CWebUser) in your model?

I’m a beginner in Yii and MVC, but if I understand MVC logic correctly, user should not be used directly in model.

Also, I wrote just a few small apps in Yii, but I never run into need of reffering user in models.

Here’s an example of code that I use:

public function relations()


	return array(

        'added_me' => array(self::HAS_ONE, 'AddedUser', 'from_user_id', 'on'=>'added_me.to_user_id='.Yii::app()->user->id),           



Irregardless of whether or not it’s bad practice, I think it would be better to make it more generic. For example:

Instead of checking if the model "added me", it makes more sense to design it so that you can check if the model "added user x". Then you just send in the Yii::app()->user->id as input instead of having it hardcoded in.

It is bad practice. What if you need to create new interface on your site, for example manager who can access not only him self, but other users.

Model doesn’t need to know in which context it used. So not using current session and so on making your code more flexible.

p.s. sorry for my english