在创建时将新FOSUserBundle用户添加到默认组

时间:2013-03-11 05:56:26

标签: symfony fosuserbundle

我正在构建我的第一个严肃的Symfony2项目。我正在为我的用户/组管理扩展FOSUserBundle,我希望新用户自动添加到默认组。 我想你只需要像这样扩展User实体构造函数:

/**
 * Constructor
 */
public function __construct()
{
    parent::__construct();
    $this->groups = new \Doctrine\Common\Collections\ArrayCollection();
    // Get $defaultGroup entity somehow ???
    ...
    // Add that group entity to my new user :
    $this->addGroup($defaultGroup);
}

但我的问题是如何首先获得我的$ defaultGroup实体?

我尝试在实体中使用实体管理器,但后来我意识到它是愚蠢的,Symfony抛出错误。我搜索了这个,但发现除了setting up a service for that之外没有真正的解决方案......虽然这对我来说似乎很不清楚。

2 个答案:

答案 0 :(得分:10)

好的,我开始致力于实现artworkad的想法。

我做的第一件事是在composer.json中将FOSUserBundle更新为2.0.*@dev,因为我使用的是v1.3.1,它没有实现FOSUserEvents类。这是订阅我的注册活动所必需的。

// composer.json
"friendsofsymfony/user-bundle": "2.0.*@dev",

然后我添加了一项新服务:

<!-- Moskito/Bundle/UserBundle/Resources/config/services.xml -->
<service id="moskito_bundle_user.user_creation" class="Moskito\Bundle\UserBundle\EventListener\UserCreationListener">
    <tag name="kernel.event_subscriber" alias="moskito_user_creation_listener" />
        <argument type="service" id="doctrine.orm.entity_manager"/>
</service>

在XML中,我告诉服务我需要通过参数doctrine.orm.entity_manager访问Doctrine。然后,我创建了Listener:

// Moskito/Bundle/UserBundle/EventListener/UserCreationListener.php

<?php
namespace Moskito\Bundle\UserBundle\EventListener;

use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Doctrine\ORM\EntityManager;

/**
 * Listener responsible to change the redirection at the end of the password resetting
 */
class UserCreationListener implements EventSubscriberInterface
{
    protected $em;
    protected $user;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    /**
     * {@inheritDoc}
     */
    public static function getSubscribedEvents()
    {
        return array(
            FOSUserEvents::REGISTRATION_SUCCESS => 'onRegistrationSuccess',
        );
    }

    public function onRegistrationSuccess(FormEvent $event)
    {
        $this->user = $event->getForm()->getData();
        $group_name = 'my_default_group_name';
        $entity = $this->em->getRepository('MoskitoUserBundle:Group')->findOneByName($group_name); // You could do that by Id, too
        $this->user->addGroup($entity);
        $this->em->flush();

    }
}

基本上就是这样!

每次注册成功后,都会调用onRegistrationSuccess(),因此我会让用户通过FormEvent $event并将其添加到我通过Doctrine获取的默认组中。

答案 1 :(得分:3)

您没有说明您的用户是如何创建的。当某些管理员创建用户或您有自定义注册操作时,您可以在控制器的操作中设置该组。

$user->addGroup($em->getRepository('...')->find($group_id));

但是,如果您在注册时使用fosuserbundles build,则必须挂钩控制器:https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/controller_events.md并使用事件监听器。