Php 使用FOSUserBundle在Symfony中注册后设置角色\用户
我正在尝试为注册后的每个用户设置默认角色(Php 使用FOSUserBundle在Symfony中注册后设置角色\用户,php,symfony,Php,Symfony,我正在尝试为注册后的每个用户设置默认角色(role\u USER)。我在FOS注册控制器中尝试过类似的方法: $user->setRoles(array('ROLE_USER')); 但是在fos_users表中注册后,角色列为空。想知道为什么吗?要在数据库中保留默认角色,需要在用户实体中重写User::setRoles()方法: public function addRole($role) { $role = strtoupper($role); if (!in_arra
role\u USER
)。我在FOS注册控制器中尝试过类似的方法:
$user->setRoles(array('ROLE_USER'));
但是在
fos_users
表中注册后,角色列为空。想知道为什么吗?要在数据库中保留默认角色,需要在用户实体中重写User::setRoles()方法:
public function addRole($role)
{ $role = strtoupper($role);
if (!in_array($role, $this->roles, true)) {
$this->roles[] = $role;
}
return $this;
}
还有另外两个方法可以做到这一点:1) 最简单的方法是重写实体构造函数:
public function __construct()
{
parent::__construct();
$this->roles = array('ROLE_USER'); }
2) 第二种方法是在注册成功事件上注册一个事件侦听器,并使用$Event->getForm()->getData()
访问用户并对其进行修改,请看:
// src/Acme/DemoBundle/EventListener/RegistrationListener.php
namespace Acme\DemoBundle\EventListener;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
enter code here
class RegistrationListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_SUCCESS => 'onRegistrationSuccess',
);
}
public function onRegistrationSuccess(FormEvent $event)
{
$rolesArr = array('ROLE_USER');
/** @var $user \FOS\UserBundle\Model\UserInterface */
$user = $event->getForm()->getData();
$user->setRoles($rolesArr);
}
}
此外,该服务需要注册如下:
// src/Acme/DemoBundle/Resources/config/services.yml
services:
demo_user.registration_listener:
class: Acme\DemoBundle\EventListener\RegistrationListener
arguments: []
tags:
- { name: kernel.event_subscriber }