好的,我开始着手实现artartad的想法。
我做的第一件事是在 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 doctrine.orm.entity_manager
。然后,我创建了 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 获得的默认组中。