如何使用 Symfony 和 TranslatorInterface 翻译描述命令?

How to translate description Command with Symfony and TranslatorInterface?

我有一个使用 Symfony 3.4+ 的项目。翻译器组件运行良好。 我可以在 execute 方法中的 Command 对象中使用它,但我不能在 configure 方法中使用它。译者为空

class TestCommand extends Command
{    
    /**
     * Translator.
     *
     * @var TranslatorInterface
     */
    protected $translator;

    /**
     * DownloadCommand constructor.
     *
     * @param TranslatorInterface $translator
     */
    public function __construct(TranslatorInterface $translator)
    {
        parent::__construct();

        $this->translator = $translator;
    }

    protected function configure()
    {

        dump($this->translator);

        $this
            ->setName('app:test')
            ->setDescription('Test command description.')
            ->setHelp('Test command help.');
        //I cannot write $this->setHelp($this->translation->trans('...'));
        //because translator is still null
    }

    /**
     * Execute the command.
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     *
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output): ?int
    {
        $output->writeln($this->translator->trans('command.test.translation'));

        return 0;
    }

}

这是输出:

C:\test>php bin/console app:test

command.test is well translated

TestCommand.php on line 48: null

为什么编译器接口没有在配置方法中初始化?

如何在配置方法中初始化翻译界面?

您需要像这样在 services.yml 文件中配置您的 TestCommand 配置

#app/config/services.yml
AppBundle\Command\TestCommand:
    arguments:
        $translator: '@translator'

基础命令classcalls configure() method in its constructor。所以如果你 想要在你的命令配置中使用一些自动装配的字段,你必须先在你的构造函数中设置这些字段然后调用 parent::__construct();,它调用 $this->configure();

在您的情况下,正确的代码应如下所示:

public function __construct(TranslatorInterface $translator)
{
    $this->translator = $translator;

    parent::__construct();
}