symfony - 订户呼叫两次 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 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 版本中,事件侦听器和订阅者会以他们的类名作为键自动注册(在某些默认条件下 - 必须阅读该主题)。因此,无需将它们显式注册为服务。我还是这样做了,但是使用任意键而不是类名,将有两个服务。
推荐阅读
- c# - 第三方 sdk dll 适用于 WPF 但不适用于 UWP
- php - session_unset() 的目的是什么?
- ios - Type Inference in tuples?
- r - 分组和绘图的功能?-R
- ruby-on-rails - Rails act_as_votable 使用 AJAX 停止页面重新加载
- excel - 如何在其工作表范围之外调用 ActiveX 过程?
- azure-functions - 从 Azure 函数发布到自定义端口
- c++ - Write IMU data to csv file using buffer and overflow buffer?
- aws-lambda - 嵌套 JSON 对象应如何从 CloudFormation 传递到 Lambda 函数?
- javascript - 尝试通过单击事件侦听器使用 Javascript 更改显示样式