[英]Symfony Console ContainerAwareCommand $this->getContainer() produces Fatal error
[英]$this->getContainer() is returning null in Symfony 3.x for Command
我正在做一個項目。 我有一些自定義驗證器,它基本上在保存任何新記錄之前檢查我的數據庫中的某些數據完整性。 因此,對於該檢查,我需要訪問 Doctrine 實體管理器。 所以下面是我的代碼。
自定義驗證器.php
<?php
namespace Custom\Validator;
use ....
/**
* Class CustomValidator
* @package Custom\Validator
*/
class CustomValidator extends AbstractModel
{
public function validate()
{
//my validation rules
}
}
這個 AbstractModel 類基本上實現了 ContainerAwareInterface,如下所示:
抽象模型.php
<?php
namespace Custom\Model;
use ....
abstract class AbstractModel implements ContainerAwareInterface
{
/**
* @var ContainerInterface
*/
protected $container;
public function setContainer(ContainerInterface $container)
{
$this->container = $container;
}
/**
* @return ContainerInterface
*/
protected function getContainer()
{
return $this->container;
}
/**
* @return ObjectManager
*/
public function getObjectManager()
{
return $this->getContainer()->get('doctrine')->getManager();
}
/**
* @param $entityClass
* @return ObjectRepository
*/
public function getRepository($entityClass)
{
return $this->getObjectManager()->getRepository($entityClass);
}
}
在我的service.yml
文件中,我定義了 AbstractModel 依賴項,如下所示:
services:
custom.abstract_model:
class: Custom\Model\AbstractModel
abstract: true
public: true
calls:
- [setContainer, ["@service_container"]]
現在,當我嘗試運行驗證器時,出現以下錯誤:
Call to a member function get() on null
這表示 AbstractModel 類中的這一行。
return $this->getContainer()->get('doctrine')->getManager();
我的實現有什么問題嗎? 我試圖搜索,但沒有找到任何有用的解決方案。
更新
我相信我沒有解釋整個場景的 10%,而那 10% 是至關重要的部分。 我實際上是在CustomCommand
使用這個CustomValidator
。 這是主要問題,如果有人以后遇到類似的問題,我將在下面解釋。
CustomValidator 需要在 services.yaml 中指定父服務。 我相信以下方法可以解決問題:
services:
Custom\Validator\CustomValidator:
parent: '@custom.abstract_model'
請參閱: https : //symfony.com/doc/3.4/service_container/parent_services.html
首先,感謝@Trappar 回答我的問題。 他的回答非常適合我之前描述的場景。 但是我沒有把全部細節都寫出來,缺少的部分是最重要的部分。
所以,當我更新我的問題時,我現在將解釋這個場景。
我有一個看起來像這樣的CustomCommand
:
<?php
namespace Custom\Command;
class CustomCommand extends Command
{
protected function configure()
{
//my configuration
}
protected function execute(InputInterface $input, OutputInterface $output)
{
//my custom code
$oValidator = new CustomValidator();
$oValidator->validate($aParams);
}
}
}
問題是,在這種情況下,我沒有得到我想要的容器。 因此,我進行了一些廣泛的研究,並發現對於這種情況,您必須擴展ContainerAwareCommand
而不是Command
。 ContainerAwareCommand
已經擴展了Command
本身,您還將獲得由應用程序內核提供的容器,如下所示。
$this->container = $application->getKernel()->getContainer();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.