Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling console command within command and get the output in Symfony2

Tags:

php

symfony

I have a few console command in Symfony2 and I need to execute one command from another command with some parameters.

After successfull execution of the second command I need to get the result (as an array for example), not the display output.

How can I do that?

like image 986
Igor Timoshenko Avatar asked Jan 21 '13 08:01

Igor Timoshenko


3 Answers

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));
}
like image 67
j0k Avatar answered Sep 22 '22 00:09

j0k


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.”

like image 25
Fnayou Avatar answered Sep 25 '22 00:09

Fnayou


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;
    } 
like image 30
Onema Avatar answered Sep 25 '22 00:09

Onema