How to correctly use silex "finish" middleware to process heavy operations in background?

1k Views Asked by At

I'm writing an app on Silex in accordance with the documentation but with some additions. I declare the route, after middleware for route and finish middleware for app.

$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 ...
});

The above code works as I need: response is sended, browser spinner is stopped, heavy operation is processed in background. But there is an open question: is it necessary to add headers to the response in after middleware and flush buffer in finish middleware? Without these manipulations server response is received only after the completion of finish middleware handler.

1

There are 1 best solutions below

4
On BEST ANSWER

I think that it is necessary.
->after( is RESPONSE event that is called when response is prepared, but not sent. In your case all necessary headers to close connection when browser receives response are added.
->finish( is TERMINATE event that is called after response was sent. flush() - I think that it used to flush response from server buffer to browser.