ZF2 response view and continue processing another code after this http response

528 Views Asked by At

I need response some variables immediately and continue executing another process in Zend Framework 2, this code could help:

public function wstestsAction(){

//This variables needs to be responded immediately
$response["response"] = true;
$response["message"] = "Msg Test";

//This process could take 1 minute
$libraryInstance = new libraryInstance();
$sendData = $libraryInstance->sendData("params");

$varsToView["resultJson"] = \Zend\Json\Json::encode($response);
$viewModel = new ViewModel($varsToView);
$viewModel->setTerminal(true);
return $viewModel;}

In the view (wstests.phtml) I have this code:

<?=$this->resultJson?>

Thanks!!!

2

There are 2 best solutions below

0
On

It works perfect.

    public function wstestsAction(){

    //This variables needs to be responded immediately
    $response["response"] = true;
    $response["message"] = "Msg Test";

    //----------------------------------------//
    ob_end_clean();
    header("Connection: close");
    ignore_user_abort(); //optional
    ob_start();
    //----------------------------------------//
    $varsToView["resultJson"] = \Zend\Json\Json::encode($response);
    $this->layout('layout/json');
    $viewModel = new ViewModel($varsToView);
    $viewModel->setTemplate('application/test/wstests.phtml');
    $viewRender = $this->getServiceLocator()->get('ViewRenderer');
    $html = $viewRender->render($viewModel);
    echo $html;
    //----------------------------------------//
    $size = ob_get_length();
    header("Content-Length: $size");
    ob_end_flush(); // Strange behaviour, will not work
    flush();            // Unless both are called !
    session_write_close(); // Added a line suggested in the comment
    //----------------------------------------//
    //This process could take 1 minute
    $libraryInstance = libraryInstance();
    $sendData = $libraryInstance->sendData("params");

}
3
On

I would recommend using a cron task to do processes that take a while. You would need to store the parameters you are looking to send in some type of storage (or even a DB).

From there you could run a cron task every 5 minutes to check for new data to submit/process (using PHP).

This would be the ideal route if you want your pages to render as fast as the others.

Hope this helps.