如何用Symfony和TranslatorInterface翻译description命令?

问题描述 投票:0回答:2

我有一个使用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翻译得很好

第48行的TestCommand.php:null

为什么在configure方法中没有初始化转换器接口?

如何在configure方法中初始化转换器接口?

php symfony command translation
2个回答
1
投票

基本命令类calls configure() method in its constructor。因此,如果要在命令配置中使用某些自动装配字段,则必须首先在构造函数中设置这些字段,然后调用parent::__construct();,它调用$this->configure();

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

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

    parent::__construct();
}

-1
投票

你需要在services.yml文件中配置你的TestCommand配置

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

© www.soinside.com 2019 - 2024. All rights reserved.