Hey-yii, dudes!
I’ve found myself duplicating many methods from User model to WebUser component.
For example, i needed getAvatar() function, so i could do something like that in main layout:
<img src="<?php echo Yii::app()->user->avatar;?>" />
I also need that WebUser::getAvatar() functionality in User model, so the following would be also possible:
foreach($comments as $commentModel) {
//...
<img src="<?php $commentModel->author->avatar; ?>" />
//...
}
$commentModel is an object of Comment model, and it has relation to User model ($commentModel->author)
Now, at first I was just duplicating methods between WebUser component and User model, but then I looked at behaviors and I think there is a way to use User model’s methods in WebUser component, but I can’t seem to figure out the right way to do that.
So, here’s what i did:
- Added "user" behavior to WebUser component:
class WebUser extends CWebUser {
public $behaviors = array(
'user' => array(
'class' => 'User'
)
);
//...
}
- Modified User model:
class User extends CActiveRecord implements IBehavior
{
// IBehavior
private $_enabled;
private $_owner;
public function attach($owner) {
$this->_owner=$owner;
}
public function detach($owner) {
$this->_owner=null;
}
public function getEnabled() {
return $this->_enabled;
}
public function setEnabled($value) {
$this->_enabled=$value;
}
// IBehavior end
//...
}
I have a feeling like i miss something, because
echo 'Email: '.Yii::app()->user->email;
Won’t display current user’s email. Do i have to alter something at auth point to make it work? Any help would be much appreciated!