Symfony2 FOSUserBundle自动与另一个实体相关

时间:2014-12-13 22:35:51

标签: symfony orm doctrine entity fosuserbundle

我最近在我的网站上实施了FOSUserBundle作为登录程序。我希望它扩展Author类。因此,每当通过FOSUSerBundle注册新用户时,都会在Author类中创建一个新条目。在Author类中,我设置了slug,createdAt和其他有用的参数。我想从FOSUserBundle传递给Authot实体的字段是" Name"领域。然后我想级联FOSUser实体,如果删除它,也删除Author实体。

如图所示FOSUserBundle.username => Author.name

我不知道如何实现此代码,只是它具有@ ORM / OneToOne关系。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您必须在用户注册完成后手动插入作者。 FOSUserBundle提供了一种挂钩事件的方法,例如邮政注册完成。您可以为FOSUserEvents::REGISTRATION_COMPLETED事件创建一个监听器,并在那里创建您的Author实体。

请参阅此处的文档:https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/controller_events.md

例如:

<强> services.yml:

services:
    my_user_registration_service:
        class: MyBundle\EventListener\MyUserRegistrationListener
        arguments: [@doctrine.orm.entity_manager]
        tags:
            - { name: kernel.event_subscriber }

<强> MyUserRegistrationListener:

namespace MyBundle\EventListener;

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

class EventSubscriber implements EventSubscriberInterface
{
    private $em;

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

    public static function getSubscribedEvents()
    {
        return array(
            FOSUserEvents::REGISTRATION_COMPLETED => 'addAuthor',
        );
    }

    public function addAuthor(FilterUserResponseEvent $event)
    {
        $user = $event->getUser();

        $author = new Author();
        $author->setName($user->getUsername();

        $this->em->persist($author);
        $this->em->flush();
    }
}