如何正确使用 silex "finish" 中间件在后台处理繁重的操作?
How to correctly use silex "finish" middleware to process heavy operations in background?
我正在根据文档在 Silex 上编写一个应用程序,但添加了一些内容。我在路由的中间件之后声明路由,并为应用程序完成中间件。
$app->put('/request/', function (Request $request) use ($app) {
// ... some code here ...
return $app->json(['requestId' => $requestId], 201);
})->bind('create_request')
->after(function(Request $request, Response $response) {
$contentLength = mb_strlen($response->getContent(), 'utf-8');
$response->headers->set('Content-length', $contentLength, true);
$response->headers->set('Connection', 'close', true);
});
$app->finish(function (Request $request, Response $response, Application $app) {
flush();
// ... generate big pdf file, attach it to email and send via swiftmailer ...
});
以上代码按我的需要工作:发送响应,停止浏览器微调器,在后台处理繁重的操作。但是有一个悬而未决的问题:after中间件的response和finish中间件的flush buffer有必要加headers吗?如果没有这些操作,只有在完成中间件处理程序完成后才会收到服务器响应。
我觉得有必要
->after(
是 RESPONSE
事件,在响应准备好但不发送时调用。在您的情况下,添加了浏览器收到响应时关闭连接所需的所有 headers。
->finish(
是发送响应后调用的 TERMINATE
事件。 flush()
- 我认为它用于将响应从服务器缓冲区刷新到浏览器。
我正在根据文档在 Silex 上编写一个应用程序,但添加了一些内容。我在路由的中间件之后声明路由,并为应用程序完成中间件。
$app->put('/request/', function (Request $request) use ($app) {
// ... some code here ...
return $app->json(['requestId' => $requestId], 201);
})->bind('create_request')
->after(function(Request $request, Response $response) {
$contentLength = mb_strlen($response->getContent(), 'utf-8');
$response->headers->set('Content-length', $contentLength, true);
$response->headers->set('Connection', 'close', true);
});
$app->finish(function (Request $request, Response $response, Application $app) {
flush();
// ... generate big pdf file, attach it to email and send via swiftmailer ...
});
以上代码按我的需要工作:发送响应,停止浏览器微调器,在后台处理繁重的操作。但是有一个悬而未决的问题:after中间件的response和finish中间件的flush buffer有必要加headers吗?如果没有这些操作,只有在完成中间件处理程序完成后才会收到服务器响应。
我觉得有必要
->after(
是 RESPONSE
事件,在响应准备好但不发送时调用。在您的情况下,添加了浏览器收到响应时关闭连接所需的所有 headers。
->finish(
是发送响应后调用的 TERMINATE
事件。 flush()
- 我认为它用于将响应从服务器缓冲区刷新到浏览器。