Calling console command within command and get the output in Symfony2

Here you can have a basic command inside a command. The output from the second command can be a json, then you just have to decode the output json to retrieve your array.

$command = $this->getApplication()->find('doctrine:fixtures:load');
$arguments = array(
    //'--force' => true
    ''
);
$input = new ArrayInput($arguments);
$returnCode = $command->run($input, $output);

if($returnCode != 0) {
    $text .= 'fixtures successfully loaded ...';
    $output = json_decode(rtrim($output));
}

you have to pass the command in the arguments array, and to avoid the confirmation dialog in doctrine:fixtures:load you have to pass --append and not --force

    $arguments = array(
    'command' => 'doctrine:fixtures:load',
    //'--append' => true
    ''
);

or it will fail with error message “Not enough arguments.”


There is an new Output class (as of v2.4.0) called BufferedOutput.

This is a very simple class that will return and clear the buffered output when the method fetch is called:

    $output = new BufferedOutput();
    $input = new ArrayInput($arguments);
    $code = $command->run($input, $output);

    if($code == 0) {
        $outputText = $output->fetch();
        echo $outputText;
    } 

Tags:

Php

Symfony