I need to execute a long-lasting command within a controller of my Symfony2 application and to return to the user in real time the output of the terminal.
I have read this:
http://symfony.com/doc/current/components/process.html#getting-real-time-process-output
I can't figure out how to print in real time the terminal output in a Twig template.
EDIT: Thanks to the Matteo's code and users comments, the final implementation is:
/**
* @Route("/genera-xxx-r", name="commission_generate_r_xxx")
* @Method({"GET"})
*/
public function generateRXXXsAction()
{
//remove time constraints if your script last very long
set_time_limit(0);
$rFolderPath = $this->container->getParameter('xxx_settings')['r_setting_folder_path'];
$script = 'R --slave -f ' . $rFolderPath . 'main.R';
$response = new StreamedResponse();
$process = new Process($script);
$response->setCallback(function() use ($process) {
$process->run(function ($type, $buffer) {
//if you don't want to render a template, please refer to the @Matteo's reply
echo $this->renderView('AppBundle:Commission:_process.html.twig',
array(
'type' => $type,
'buffer' => $buffer
));
//according to @Ilmari Karonen a flush call could fix some buffering issues
flush();
});
});
$response->setStatusCode(200);
return $response;
}