php - 如何使用 Symfony 和 TranslatorInterface 翻译描述命令?
问题描述
我有一个使用 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:空
为什么翻译器接口没有在配置方法中初始化?
如何在配置方法中初始化翻译器接口?
解决方案
基 Command 类在其构造函数中调用 configure() 方法。所以如果你想在你的命令配置中使用一些自动装配的字段,你必须首先在你的构造函数中设置这些字段,然后调用parent::__construct();
,它调用$this->configure();
在您的情况下,正确的代码应如下所示:
public function __construct(TranslatorInterface $translator)
{
$this->translator = $translator;
parent::__construct();
}
推荐阅读
- php - 如何在字段 Symfony/Doctrine 上添加动态 CrudController
- c - C 中此 switch 语句的替代方案
- amazon-ec2 - EKS ingress-nginx 和 NLB 与 https 重定向
- php - 致命错误:未捕获的错误:找不到类“SolrClient”-Apache Solr/PHP
- c# - 我的控制器返回正确的数据,但数据表没有对其进行可视化
- android - 如何将图像 url 作为多部分发送到服务器?
- tensorflow - 使用 keras 进行深度学习的 input_shape 不兼容
- css - 如何更改或覆盖 Bootstrap 4 模板中的基本字体大小?
- spring-data - 如何在 Spring Data Azure Cosmos DB 中编写动态 sql
- conv-neural-network - 卷积神经网络中批量归一化中均值和方差的计算