[英]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.