コンストラクタ内のコンテナを直接取得しないでください。代わりに、configure
メソッドまたはexecute
メソッドで取得します。私の場合、私はこのようなexecute
メソッドの開始時にエンティティマネージャーを取得し、すべてが正常に動作しています(Symfony 2.1でテスト済み)。
protected function execute(InputInterface $input, OutputInterface $output)
{
$entityManager = $this->getContainer()->get('doctrine')->getEntityManager();
// Code here
}
私はあなたがこのエラーになり、あなたのコンストラクタでgetContainer
を呼び出しているとき、アプリケーションオブジェクトのインスタンス化がまだ行われていないと思います。エラーは何をするtyring getContainer
方法から来ている:
$this->container = $this->getApplication()->getKernel()->getContainer();
getApplication
はまだオブジェクトではないので、あなたはエラーが言っても非オブジェクトのメソッドgetKernel
呼びかけている取得します。
アップデート:新しいバージョンのSymfonyでは、getEntityManager
は廃止されました(これまでにすべて削除された可能性があります)。代わりに$entityManager = $this->getContainer()->get('doctrine')->getManager();
を使用してください。それを指してChausserありがとうございます。
アップデート2:Symfony 4では、自動配線を使用して必要なコード量を減らすことができます。
変数を持つ__constructor
を作成します。この変数は残りのコマンドでアクセスできます。これは、自動配線依存性注入スキームに従います。
class UserCommand extends ContainerAwareCommand {
private $em;
public function __construct(?string $name = null, EntityManagerInterface $em) {
parent::__construct($name);
$this->em = $em;
}
protected function configure() {
**name, desc, help code here**
}
protected function execute(InputInterface $input, OutputInterface $output) {
$this->em->getRepository('App:Table')->findAll();
}
}
コメントとコードサンプルを提供するための@ profm2のクレジット。
私は同じエラーときを過ごしています(と私は 'getContainerにアクセスしようとする: –