Menu

Call a console command from a controller (Symfony2)

The following code snippet shows how you can call a console command from your controller:

<?php

namespace AcmeDemoBundleController;

use SymfonyBundleFrameworkBundleControllerController;
use SymfonyComponentHttpFoundationResponse;

// these import the "@Route" and "@Template" annotations
use SensioBundleFrameworkExtraBundleConfigurationRoute;
use SensioBundleFrameworkExtraBundleConfigurationTemplate;

use SymfonyBundleFrameworkBundleConsoleApplication;
use SymfonyComponentConsoleInputStringInput;
use SymfonyComponentConsoleOutputStreamOutput;

class DemoController extends Controller
{
    /**
     * @Route("/command-runner/", name="_command_runner")
     */
    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());    
        
        $ret = array('response' => $response);
        return new Response(json_encode($ret));
    }
}

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.

Facebook Comments

No comments

Trả lời