【发布时间】:2025-12-02 05:15:01
【问题描述】:
我阅读了有关在 Symfony 2 中创建命令行的文档。 我想创建一个有点不同的 Command 类。确实,我想将翻译器添加为我班级的私有字段......就像这样:
<?php
namespace myVendor\myBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ThemeCommand extends ContainerAwareCommand {
private $translator;
public function __construct() {
$this->translator = $this->getContainer()->get('translator');
}
protected function configure() {
$this->setName('viewkit:color')
->setDescription($this->translator->trans('command.theme.description'))
->addArgument('theme', InputArgument::REQUIRED, 'le thème jquery');
}
protected function execute(InputInterface $input, OutputInterface $output) {
$theme = $input->getArgument('theme');
$output->writeln($this->translator->trans('command.theme.success'));
}
}
?>
你可以想象它因为构造函数而不起作用,我有这个例外:
Call to a member function getKernel() on a non-object in C:\wamp\www\viewkit\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand.php
问题是抽象类 ContainerAwareCommand 中的 getContainer 方法可能返回 null 并且由于这个类来自 Command.php 类,问题更具体地说是返回非对象(可能为 null)的 Command.php getApplication 方法..
Command.php 类的 application 字段以某种方式被填充,但是由于我的 ThemeCommand 中有我的构造函数,所以出现了问题
所以我的问题是: 如何在我的 ThemeCommand 类中拥有私有字段并使用完善的构造函数对其进行初始化
谢谢
我做了另一个测试,摆脱了构造函数并像文档中那样做......同样的问题,构造函数不是问题,但 getContainer 没有返回对象,因为 Command.php 中的 getApplication为空
【问题讨论】:
-
你如何从 CLI 调用你的命令?
-
我用的是netbeans,所以加载了命令行,此时出现异常...如果我不使用翻译器,它可以正常工作
标签: symfony command-line