【发布时间】:2019-02-17 15:02:17
【问题描述】:
我有一个使用 Symfony 3.4+ 的项目。 Translator 组件运行良好。 我可以在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:空
为什么配置方法中没有初始化翻译器接口?
configure方法中如何初始化translator接口?
【问题讨论】:
-
你能不能先设置翻译器再调用
parent::__construct()? -
感谢@Snegirekk,它有效!我让你发布答案来验证它。
标签: php symfony command translation