1

我阅读了有关在 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 类的应用程序字段被填充了,但是由于我的ThemeCommand中有我的构造函数,所以出现了问题

所以我的问题是:我怎样才能在我的 ThemeCommand 类中有私有字段并用一个做得好的构造函数初始化它们

谢谢


我做了另一个测试,摆脱了构造函数并像文档中那样做......同样的问题,构造函数不是问题,但 getContainer 不返回对象,因为Command.php 中的getApplication为空

4

2 回答 2

2

你忘了调用父构造函数!

public function __construct() {
    parent::__construct();
    $this->translator = $this->getContainer()->get('translator');
}
于 2013-03-13T14:22:59.793 回答
2

问题是在调用configure方法时,或者在调用constructor时,应用程序对象为null。只有在执行方法中才能调用服务,因为与此同时,应用程序对象已被填充

于 2013-03-21T12:57:10.107 回答