The following code snippet shows how you can call a console command from your controller:
The above snippet will return the output of the command run (in this case "router:debug") in the response variable, which can be rendered into the your views.
You can provide any other commands and additional options by simply making changes to the string provided to the StringInput object, eg. StringInput('cache:clear --env=prod');
This snippet was tested on Symfony2 Framework version 2.3.
<?php namespace Acme\DemoBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\RedirectResponse; // these import the "@Route" and "@Template" annotations use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Component\Console\Input\StringInput; use Symfony\Component\Console\Output\StreamOutput; class DemoController extends Controller { /** * @Route("/command-runner/", name="_command_runner") * @Template() */ public function command_runnerAction() { $kernel = $this->container->get('kernel'); $app = new Application($kernel); $input = new StringInput('router:debug'); $output = new StreamOutput(fopen('php://temp', 'w')); $app->doRun($input, $output); rewind($output->getStream()); $response = stream_get_contents($output->getStream()); return array('response' => $response); } }
The above snippet will return the output of the command run (in this case "router:debug") in the response variable, which can be rendered into the your views.
You can provide any other commands and additional options by simply making changes to the string provided to the StringInput object, eg. StringInput('cache:clear --env=prod');
This snippet was tested on Symfony2 Framework version 2.3.