【问题标题】:Listener not triggered by the event dispatcher事件调度程序未触发侦听器
【发布时间】:2018-01-24 15:30:52
【问题描述】:

我想在控制器返回响应后执行 symfony 函数。

我该怎么做?

这是我使用的所有类:

定义所有事件:这里我们在这个类中只定义了一个事件

<?php
# AcmeEvents.php
namespace test\apiBundle;

final class AcmeEvents
{
    const AFTER_RETURN_RESPONSE = "acme.after_return_response";
}

定义监听器

<?php
#TestSubscriber.php
namespace test\apiBundle\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use test\apiBundle\AcmeEvents;

use Symfony\Component\Filesystem\Filesystem;

class TestSubscriber implements EventSubscriberInterface
{
    public function __construct()
    {
    }

    public static function getSubscribedEvents()
    {
        return array(
            AcmeEvents::AFTER_RETURN_RESPONSE => 'processingFunction'
        );
    }

    public function processingFunction(Event $event)
    {
        $fs = new Filesystem();
        $fs->touch('files/myfile.json', 0700);
    }
}

定义触发事件的控制器

<?php
#WelcomeController.php
namespace test\apiBundle\Controller;

#use all other components
use Symfony\Component\EventDispatcher\EventDispatcher;

use test\apiBundle\AcmeEvents;

class WelcomeController extends Controller
{
    public function getWelcomeAction()
    {
        # all other processes
        $event = new UploadEvent();
        $dispatcher = new EventDispatcher();
        $dispatcher->dispatch(
            'AcmeEvents::AFTER_RETURN_RESPONSE', $event
        );
        return $response;
    }
}

【问题讨论】:

  • 您的服务定义是什么?
  • acme:类:test\apiBundle\EventListener\TestSubscriber 标签:-{ 名称:kernel.event_listener,事件:acme.after_return_response }
  • 看看这个full example,看看在向客户端发送响应后如何执行一些事情(你必须监听kernel.terminate事件)。
  • 为什么你没有在 Action 中使用服务 event_dispatcher ? $this->get('event_dispatcher')->dispatch() .. 为什么是 new EventDispatcher() ??
  • @Mocrates 你为什么删除你的答案?看起来你有正确的解决方案。格式化可能需要一些工作。

标签: symfony events return dispatcher


【解决方案1】:

尝试在您的操作中获取服务调度程序而不是新实例:

替换

$dispatcher = new EventDispatcher();

通过

$this->get('event_dispatcher')->dispatch(....)

【讨论】:

  • 我已经更换了它,我仍然遇到同样的问题
  • 它还有其他东西...我将使用 dispatch(AcmeEvents::AFTER_RETURN_RESPONSE, $event); ...调用类的常量...删除引号
  • 我已经删除了报价,该操作被触发,但返回部分总是等待所有进程的结束,包括 TestSubscriber 中的 processingFunction。也许我们可以为每个事件赋予优先级,但我认为在返回调用之后不可能执行任何事情。
  • 尝试派发和收听 kernel.terminate,就像之前评论中提到的 @gp_sflover 一样...并在此事件中注册您的订阅者
  • 即使我们派发 kernel.terminate 事件,返回调用仍然是应用程序中执行的最新操作。我将尝试使用回声呼叫而不是返回。也许这是解决我的问题的唯一方法
猜你喜欢
  • 2013-05-19
  • 1970-01-01
  • 2020-09-06
  • 2021-01-14
  • 1970-01-01
  • 1970-01-01
  • 2021-11-03
  • 1970-01-01
  • 2018-08-06
相关资源
最近更新 更多