Php 如何在Symfony 3.4中从控制器调用命令?

Php 如何在Symfony 3.4中从控制器调用命令?,php,symfony,Php,Symfony,我在Symfony中创建了一个命令,用于清除缓存并从web目录中删除所有翻译。命令名为: $this->setName('dump-translations') 命令从控制台运行,但当我从控制器调用它时,会得到响应: Command "dump-translations" is not defined. 我想我错过了一些步骤,但找不到答案。 代码如下: namespace Pi\Bundle\WhiteLabelBundle\Controller; use Pi\Bundle\Whi

我在Symfony中创建了一个命令,用于清除缓存并从web目录中删除所有翻译。命令名为:

$this->setName('dump-translations')
命令从控制台运行,但当我从控制器调用它时,会得到响应:

Command "dump-translations" is not defined.
我想我错过了一些步骤,但找不到答案。 代码如下:

namespace Pi\Bundle\WhiteLabelBundle\Controller;

use Pi\Bundle\WhiteLabelBundle\Command\DumpTranslationsCommand;
use Pi\Bundle\WhiteLabelBundle\YmlReader\YmlReader;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\BrowserKit\Response;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\BufferedOutput;


class DefaultController extends Controller
{
    public function indexAction()
    {
        (new YmlReader())->readYmlFile();

        echo $this->sendSpool();

        return $this->render('Pi\WhiteLabelBundle:Default:index.html.twig');
    }

    public function sendSpool()
    {
        $application = new Application($this->get('kernel'));

        $application->setAutoExit(false);

        $input = new ArrayInput(array(
            'command' => 'dump-translations'
        ));

        $output = new BufferedOutput();
        $application->run($input, $output);

        $content = $output->fetch();

        return new Response($content);
    }
}

改进您的体系结构的可能解决方案(所以您不需要调用命令)。您应该将功能提取到服务,然后您可以在控制器和命令中使用您的服务,而无需从控制器运行命令。你的代码库会更清晰


下一个可能的事情-通过IMO运行命令最干净的解决方案是第一个(服务)