我正在构建我的第一个严肃的 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 抛出了一个错误。我用谷歌搜索了这个,但没有找到真正的解决方案,除了也许为此设置服务 https://stackoverflow.com/questions/4108291/using-entitymanager-inside-doctrine-2-0-entities?answertab=votes#tab-top...虽然这对我来说似乎很不清楚。
好的,我开始致力于实施艺术品广告 https://stackoverflow.com/users/401025/artworkad's idea.
我做的第一件事是将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 中,我告诉服务我需要通过参数访问 Doctrinedoctrine.orm.entity_manager
。然后,我创建了监听器:
// 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 获得的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)