Epo*_*pok 26 symfony fosuserbundle
版本:Symfony 2.2
当用户在我的网站上注册时,我正在尝试添加默认角色.我使用FOSUserBundle,我看到当用户注册角色字段在数据库中为空时.我从这个庞大的包开始,它不是很容易理解.所以我阅读了所有的文档,我不知道该怎么做.
现在,我创建一个事件来动态添加这个角色,但它不起作用(我没有错误,但我的数据库仍然是空的)我甚至不知道这是做这个的好方法吗?
我的活动:
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class AddDefaultRoleListener implements EventSubscriberInterface {
private $container;
public function __construct(Container $container)
{
$this->container = $container;
}
/**
* {@inheritDoc}
*/
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_SUCCESS => 'onAddDefaultRoleSuccess',
);
}
public function onAddDefaultRoleSuccess(FormEvent $event)
{
$doctrine = $this->container->get('doctrine');
$em = $doctrine->getManager();
$user = $event->getForm()->getData();
$user->addRole('ROLE_USER');
//$user->setRoles(array('ROLE_USER'));
$em->persist($user);
}
}
Run Code Online (Sandbox Code Playgroud)
如你所见,我创建一个简单的事件,听取REGISTRATION_SUCCESS,但似乎没有任何工作.这是我第一次尝试使用事件和服务.所以,如果有人有建议,我会接受:)
谢谢
Ray*_*Air 39
FOSUserBundle的主要贡献者(在此处链接的注释中)指示的建议方法是在REGISTRATION_SUCCESS事件上注册事件监听器,并使用它$event->getForm()->getData()来访问用户并对其进行修改.遵循这些准则,我创建了以下监听器(它有效!):
<?php
// src/Acme/DemoBundle/EventListener/RegistrationListener.php
namespace Acme\DemoBundle\EventListener;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Listener responsible for adding the default user role at registration
*/
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);
}
}
Run Code Online (Sandbox Code Playgroud)
此外,该服务需要注册如下:
// src/Acme/DemoBundle/Resources/config/services.yml
services:
demo_user.registration_listener:
class: Acme\DemoBundle\EventListener\RegistrationListener
arguments: []
tags:
- { name: kernel.event_subscriber }
Run Code Online (Sandbox Code Playgroud)
请注意,在User类__construct()中添加默认角色可能会出现一些问题,如此其他答案所示.
alv*_*pgl 37
我所做的是覆盖实体构造函数:
这是我的Entity/User.php的一部分
public function __construct()
{
parent::__construct();
// your own logic
$this->roles = array('ROLE_USER');
}
Run Code Online (Sandbox Code Playgroud)
这是懒惰的方式.如果你想要正确和更好的方式,请参阅@RayOnAir 答案
| 归档时间: |
|
| 查看次数: |
34371 次 |
| 最近记录: |