如何在Symfony2中为用户分配默认角色 [英] How can I assign default role to user in Symfony2
问题描述
我要在用户注册后为其分配默认角色.我已经实现了SonataUserBundle扩展的FOSUserBundle.不幸的是,SonataUserBundle要求FOSUserBundle〜1.3,而事件监听器仅在FOSUserBundle 2.0以后.
I want to assign default role to user after he is registered. I have implemented FOSUserBundle extended by SonataUserBundle. Unfortunetly SonataUserBundle requires FOSUserBundle ~1.3 and event listeners are only since FOSUserBundle 2.0.
除了eventListener或FOSUserBundle控制器重写之外,还有其他方法可以解决此问题吗?也许我错过了Yaml中的某种选择?看来这是很标准的问题,但我仍然是symfony2的新手...
Is there another way to solve this problem except eventListener or FOSUserBundle controller override ? Maybe some kind of option in yaml I have missed ? It seems quite standard problem but I am still new in symfony2...
推荐答案
您可以覆盖用户类的getRoles()方法:
You can overwrite the getRoles() method of you user class :
public function getRoles()
{
$roles = parent::getRoles();
if ($this->enabled) {
switch ($this->type) {
case self::TYPE_1:
$roles[] = 'ROLE_TYPE_1';
break;
case self::TYPE_2:
$roles[] = 'ROLE_TYPE_2';
break;
}
}
return array_unique($roles);
}
按用户类型添加角色
edit: add role per user type
这篇关于如何在Symfony2中为用户分配默认角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!