在Laravel中,如何将项目添加到控制器中的数组,然后通过App :: finish()响应后进行处理 [英] In Laravel, how can I add items to array in controller and then process after response via App::finish()
问题描述
我正在创建一个分析存储过程(使用弹性搜索),需要从控制器添加要以弹性形式存储的项目.但是然后我想等到响应发送到用户之后才真正进行处理.我不希望用户必须等待此过程完成才能获得服务器响应.
I am creating an analytics storage process (using elastic search) where I need to add the items to be stored in elastic from my controller. But then I want to wait until after the response has been sent to the user to actually do the processing. I don't want the user to have to wait for this process to complete before getting the server response.
我计划使用以下命令运行处理部分:
I am planning on running the processing part using:
App::finish(function(){
// DO THE PROCESSING
})
我知道这将在发送响应后运行.但是,我不确定如何获取已在控制器(或任何类)中编译的数据以在App :: finish()关闭方法中引用.
I know that this will run after the response has been sent. However, I am not sure how to get the data which has been compiled in a controller (or any class) to be referenced in the App::finish() closure method.
我尝试使用App::singleton()
,但是在许多情况下,我需要能够不断地设置"数据,我不能只设置一次.我想我实际上是在寻找可以操纵的全局变量,但我知道Laravel中不存在该变量.
I have tried using App::singleton()
but there are many instances where I need to be able to continually 'set' the data, I can't just set it once. I guess I am essentially looking for a global variable that I can manipulate but I know that doesn't exist in Laravel.
另一种选择是使用Session::push()
和Session::get()
,但是现在我的会话存储使用此应用程序的memcached,并且当我只想存储所需的数据时,我不想在memcached上进行其他I/O操作保存在临时存储器中.
Another option is to use Session::push()
and Session::get()
but right now I have my Session storage using memcached for this app and I would rather not do additional I/O on memcached when I could just be storing the data needed to be saved in temporary memory.
似乎我只需要一个简单的容器来读写,该容器仅保存在内存中,但在Laravel文档中找不到.
Seems like I just need a simple container to write to and read from which is saved only in memory but I cannot find that in the Laravel docs.
推荐答案
您可以使用"use"将数据传递给闭包.
You can pass data to the closure using "use".
在将数据返回给用户之后,我最终使用了类似的方法将数据存储在缓存中.
I ended up using something like this for storing data in the cache after returning the data to the user.
App::finish(function($request, $response) use ($id, $json){
Cache::put('key_'.$id, $json, 1440);
});
这篇关于在Laravel中,如何将项目添加到控制器中的数组,然后通过App :: finish()响应后进行处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!