监听器不是由事件调度程序触发的

时间:2018-01-24 15:30:53

标签: symfony events return dispatcher

我想在控制器中返回响应后执行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;
    }
}

1 个答案:

答案 0 :(得分:0)

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

替换

$dispatcher = new EventDispatcher();

通过

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