首页 > 解决方案 > 订户呼叫两次 symfony

问题描述

我在提交表单后使用 FOSUserEvents 但订阅者调用了两次。

这样我的验证码第一次有效,第二次无效

这是我的代码

<?php

namespace AppBundle\EventListener;



class CaptchaSubscriber implements EventSubscriberInterface
{

    private $router;
    private $requestStack;
    private $templating;

    /**
     * RedirectAfterRegistrationSubscriber constructor.
     */
    public function __construct(RouterInterface $router, RequestStack $requestStack, \Twig_Environment $templating)
    {
        $this->router = $router;
        $this->requestStack = $requestStack;
        $this->templating = $templating;

    }

    public function onRegistrationInit(GetResponseUserEvent $event)
    {

        if ($this->requestStack->getMasterRequest()->isMethod('post')) {
            
            ...handle captcha...

        }

    }

    public static function getSubscribedEvents()
    {
        return [
            FOSUserEvents::REGISTRATION_INITIALIZE => 'onRegistrationInit'
        ];
    }        
}

我的 symfony 是 3.3

更新

我添加了

        $event->stopPropagation();

使用此代码段代码有效,但我不知道这是否是最佳实践

标签: symfony

解决方案


在我的 symfony 4.2 中,它是否发生取决于服务定义。

如果我这样定义服务,我的订阅者会注册两次:

# oauth process listener
app.subscriber.oauth:
    class: App\EventListenerSubscriber\OauthSubscriber
    arguments: ['@session', '@router', '@security.token_storage', '@event_dispatcher', '@app.entity_manager.user', '@app.fos_user.mailer.twig_swift']
    tags:
        - { name: kernel.event_subscriber }

但是,如果我将定义更改为此,它只会注册一次:

# oauth process listener
App\EventListenerSubscriber\OauthSubscriber:
    arguments: ['@session', '@router', '@security.token_storage', '@event_dispatcher', '@app.entity_manager.user', '@app.fos_user.mailer.twig_swift']
    tags:
        - { name: kernel.event_subscriber }

我在 github 上发布了一个错误报告并立即得到了答案,在较新的 symfony 版本中,事件侦听器和订阅者会以他们的类名作为键自动注册(在某些默认条件下 - 必须阅读该主题)。因此,无需将它们显式注册为服务。我还是这样做了,但是使用任意键而不是类名,将有两个服务。


推荐阅读