Symfony 2.4 execute Command from Controller

2019-07-21 16:18发布

问题:

I want to execute the command fos:elastica:populate from my controller.

I tried that code but it doesn't work, i get error = 1 the var_dump show ""

$command = 'fos:elastica:populate';
$app = new Application($this->get('kernel'));
$app->setAutoExit(false);
$input = new StringInput($command);
$output = new ConsoleOutput;
$error = $app->run($input, $output);
var_dump($error);
var_dump(stream_get_contents($output->getStream());

Any ideas ?

I try a different code.....

    $command = $this->get('FosElasticaPopulateService');
    $input = new StringInput('');

    $output = new ConsoleOutput();
    ladybug_dump($input);
    // Run the command
    $retval = $command->run($input, $output);

    if(!$retval)
    {
        echo "Command executed successfully!\n";
    }
    else
    {
        echo "Command was not successful.\n";
    }
    var_dump(stream_get_contents($output->getStream()));

It say: 'The "no-interaction" option does not exist.' at Input ->getOption ('no-interaction') in the PopulateCommand.

if i change my code with:
$input = new StringInput('--no-interaction');

It say: 'The "--no-interaction" option does not exist.' at
'ArgvInput ->addLongOption ('no-interaction', null) '

回答1:

Step by step, how to run cache clear command: app/console cac:cle --env=(current_env) from controller.

At first, make sure to register command as service (service.yml):

xxx.cache.clear:
    class: Symfony\Bundle\FrameworkBundle\Command\CacheClearCommand
    calls:
        - [setContainer, ["@service_container"] ]

Conde in your controller:

$command = $this->container->get('xxx.cache.clear');
$input = new ArgvInput(array('--env=' . $this->container->getParameter('kernel.environment')));
$output = new ConsoleOutput();
$command->run($input, $output);

That's all. | tested on symfony 2.4



回答2:

First of all: check if that command is already registered as a service. If not register it yourself

FosElasticaPopulateService:
    class: Path\To\Bundle\Class
    calls:
        - [setContainer, ["@service_container"] ]

then into your controller

$output = new ConsoleOutput;
$command = $this->get('FosElasticaPopulateService');
$command->run(null, $ouput); //null here is for input parameters; if you need them, insert

if it is already registered, just use it as showed above


Ok, I got it: my solution is an alternative one (maybe more suitable for your own command if bundle's command aren't registered as services natively). Reading some documentation, your method should work aswell. You've got an error that blocks you:

$output = new ConsoleOutput; should be $output = new ConsoleOutput();



回答3:

If you need the code in the command to be executed in the controller, put the code in its own class and call that class in the controller and the command.