4

I want to return the final user a response, before I'm making all the hard processing data.

I want to simply get a request from user, return a response, it could be a simple json,

and than the user will see the data, but in my server side I would continue my rest of the processing, calling analytics, changing DB and other.

something like this idea: continue processing php after sending http response

Community
  • 1
  • 1
Tzook Bar Noy
  • 11,337
  • 14
  • 51
  • 82
  • 2
    Possible duplicate of [Symfony run code after response was sent](https://stackoverflow.com/questions/35219537/symfony-run-code-after-response-was-sent) – Omn Jan 20 '18 at 05:17

4 Answers4

5

For heavier tasks you should use the kernel.terminate Event. So any task in this event is performed, after the response was sent. This is the way, how the swiftmailer memory spool works.

conradkleinespel
  • 6,560
  • 10
  • 51
  • 87
Emii Khaos
  • 9,983
  • 3
  • 34
  • 57
1

This maybe a late answer, but the mentioned scenario makes a perfect use of Queues. Using a library like LeezyPheanstalkBundle will make usage of beanstalkd a lot easier.

What happens is:
1. Receive user request
2. Add job to queue (very fast)
3. Return server response
4. a worker retrieve the job and processes it.

Nagy Wesley
  • 111
  • 2
  • 11
0

I find that Symfony's message bus are a good solution for this.

You can send the message directly to the worker or use a transport, e.g. a Queue like @Nagy Wesley suggests.

clapas
  • 1,768
  • 3
  • 16
  • 29
-2

Check out the StreamedResponse:

$response = new StreamedResponse();
$response->setCallback(function () {
    echo 'Hello World';
    flush();
    sleep(2);
    echo 'Hello World';
    flush();
});
$response->send();

Read more here: http://symfony.com/doc/current/components/http_foundation/introduction.html#streaming-a-response

While this method has its simplicity and usefulness in certain cases, it's not the best user experience in a webpage. The HTML page will only be fully loaded at the end of your script, which may cause visual annoyances and the lack of Javascript support, incomplete CSS rendering, etc...

If you're going for the best visual experience, you could load an empty page, and then make concurrent ajax calls that will do the processing. ie. each AJAX request will process 5 records and output them.

This way you can have a progress bar or some other animation going on the page...

Webberig
  • 2,746
  • 1
  • 23
  • 19
  • StreamedResponse is noth thought for performing tasks after it. – Emii Khaos Aug 18 '13 at 10:40
  • @Pazi: As I said in my answer, it has its usefulness in certain cases, but often you want to provide feedback about the processing so ajax would be better suited. It really depends on what exactly you want to achieve. – Webberig Aug 18 '13 at 11:43