【问题标题】:How to call command form the controller in Symfony 3.4?如何从 Symfony 3.4 中的控制器调用命令?
【发布时间】:2018-08-06 13:55:11
【问题描述】:

我在 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);
    }
}

【问题讨论】:

标签: php symfony


【解决方案1】:

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

下一个可能的事情 - 通过Process 运行命令

【讨论】:

  • IMO 最干净的解决方案是第一个(服务)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-02
  • 1970-01-01
相关资源
最近更新 更多