2

我想从我的控制器执行命令 fos:elastica:populate。

我尝试了该代码,但它不起作用,我得到 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());

有任何想法吗 ?

我尝试不同的代码......

    $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()));

它说:“不存在“无交互”选项。在 PopulateCommand 中的 Input ->getOption ('no-interaction') 处。

如果我更改我的代码:
$input = new StringInput('--no-interaction');

它说:'“--no-interaction”选项不存在。' 在
'ArgvInput -> addLongOption('无交互',null)'

4

3 回答 3

3

一步一步,如何从控制器运行缓存清除命令:app/console cac:cle --env=(current_env)。

首先,确保将命令注册为服务(service.yml):

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

Conde 在你的控制器中:

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

就这样。| 在 symfony 2.4 上测试

于 2014-03-20T15:37:36.057 回答
2

首先:检查该命令是否已注册为服务。如果不自己注册

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

然后进入你的控制器

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

如果它已经注册,只需如上所示使用它


好的,我明白了:我的解决方案是另一种解决方案(如果捆绑的命令未在本机​​注册为服务,则可能更适合您自己的命令)。阅读一些文档,您的方法也应该有效。您遇到了一个阻止您的错误:

$output = new ConsoleOutput;应该$output = new ConsoleOutput();

于 2014-03-20T14:06:47.210 回答
0

如果需要在控制器中执行命令中的代码,请将代码放在它自己的类中,然后在控制器和命令中调用该类。

于 2014-03-20T14:21:40.280 回答