覆盖FOSUserBundle RegistrationController

时间:2014-03-31 08:24:00

标签: symfony fosuserbundle

在FOSUserBundle中,我需要覆盖FOSUserBundle RegistrationController,因为我需要添加它:

if($user->getType()=="Student") {
    $user->addRole("ROLE_Student");
}
else {
    $user->addRole("ROLE_TEACHER");
}

当我在vendor--->...---->registrationcontroller中添加它时,它会起作用。这就是为什么我需要覆盖注册控制器,但是如何?

1 个答案:

答案 0 :(得分:2)

不要覆盖控制器。你应该使用事件系统!创建一个订阅FOSUserEvents::REGISTRATION_COMPLETE的事件处理程序,然后执行角色添加。

文档:

听众:

class RegistrationListener implements EventSubscriberInterface
{
    public function __construct(/* ... */)
    {
        // ...
    }

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

    public function addRole(FilterUserResponseEvent $event)
    {
        $user = $event->getUser();
        // Add the role here
        // ...
    }
}

服务定义:

<service id="my_app.event.registration" class="MyApp\Event\RegistrationListener">
    <tag name="kernel.event_subscriber" />
    <!-- ... -->
</service>
相关问题