drasebt1835 2018-04-11 02:58
浏览 56

Symfony - 在Controller和EventListener之间共享数据

I'm currently using Symfony 3.4 as a stateless API, with Doctrine as an ORM. My controller loads some object from the database, does something with it, and returns a response. I have an EventListener registered for the kernel.terminate event to do post-processing after the response is sent - sending emails, etc. I'd like to have a mechanism to share objects loaded by the Controller with the EventListener, such that I don't have to do an extra database lookup in the EventListener.

Right now it looks something like this:

// Controller.php
public function fooAction(Request $request) {
   $id = $request->query->get('id');
   $bar = $this->databaseLookupBar($id);
   // do stuff to bar ...
   return new Response();
}

// EventListener.php
public function onKernelTerminate($event) {
   $request = $event->getRequest();
   $id = $request->query->get('id');
   $bar = $this->databaseLookupBar($id);
   // post-processing, send emails, etc.
}

I can think of two solutions:

1) Do it the way I'm currently doing it (1 redundant database lookup).

2) Store the object in the session, then clear the session when I'm done with it.

Is there a better solution?

  • 写回答

1条回答 默认 最新

  • dongnaoben4456 2018-04-11 04:58
    关注

    Add a property and a setter method to your event listener class:

    // EventListener.php
    
    private $bar;
    
    public function setBar($bar)
    {
        $this->bar = $bar;
    }
    
    public function onKernelTerminate($event)
    {
        $bar = $this->bar;
        // post-processing, send emails, etc.
    }
    

    Then call the setter from your controller:

    // Controller.php
    
    use Namespace\For\EventListenerClass
    
    public function fooAction(Request $request, EventListenerClass $eventListener)
    {
        $id = $request->query->get('id');
        $bar = $this->databaseLookupBar($id);
        // do stuff to bar ...
    
        $eventListener->setBar($bar);
    
        return new Response();
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100