使用信条生命周期回调来进行依赖注入


Using Doctrine Lifecycle callback for dependency Injection while hyderating

我正在使用Doctrine(没有symfony)开发php应用程序,因此没有DI容器。我在我的一个实体中使用了依赖注入,它需要一个服务。

    Class A implements Ia
    {
        public function __constructor( 'requiredServiceClass $requiredService = NULL )
        {
            if ($requiredService === NULL) {
                $this->requiredService = new 'requiredServiceClass();
            {
                $this->requiredService = $requiredService;
            }
        }
    }

一切都很好,但是当水合原则没有调用__构造函数时,依赖就没有被注入。解决这个问题的最好方法是什么?

目前我使用Doctrine生命周期事件回调一个方法来设置依赖。首先,我在实体

的映射文件中添加了生命周期回调
   <lifecycle-callbacks>
       <lifecycle-callback type="postLoad" method="setRequiredService"/>
   </lifecycle-callbacks>

然后在被调用的方法中注入依赖,使用setter依赖注入。

public function setRequiredService()
{
   $this->requiredService = new 'requiredServiceClass();
}

我的问题:这是在Doctrine中解决依赖注入的最好方法吗?它是好的传递DI参数默认为NULL吗?

谢谢,Abhinit Ravi

是否在数据库中存储此"服务"的任何信息?我不确定那是什么。

如果是,您可以将其定义为自定义数据类型。这里是关于该主题的学说文档的链接。

http://doctrine-orm.readthedocs.org/en/latest/cookbook/custom-mapping-types.html

http://docs.doctrine-project.org/en/2.0.x/cookbook/mysql-enums.html

如果它只是你需要的一些类,我不认为有任何问题,如果不知道服务是什么,我不确定,重构代码可能会更好,所以它不需要这个,但如果不知道它是做什么的,我不能说。

我说你这样做的方式是好的,不确定onLoad是否只在从数据库中提取时触发,但你可能要检查是否为空。

我可能会这样写这个类

Class A implements Ia
    {
        protected $requiredService; //null by default
        public function __constructor( 'requiredServiceClass $requiredService = NULL )
        {
            $this->setRequiredService($requiredService);
        }
       public function postLoad(){
          $this->setRequiredService();
       }
        public function setRequiredService('requiredServiceClass $requiredService = NULL)
        {
            if(NULL === $this->requiredService){
                //check if class has service - assuming you never want to set it again once it is set.
                if(NULL === $requiredService){
                    $this->requiredService = new 'requiredServiceClass();
                }else{
                    $this->requiredService = $requiredService;
                }
            }
        }
    }

 <lifecycle-callbacks>
       <lifecycle-callback type="postLoad" method="postLoad"/>
   </lifecycle-callbacks>

我的理由是。

    这样,在注入服务之前,所有的检查都是正确的类。
  1. 从代码中可以清楚地看到使用了生命周期回调。
  2. 更好地遵循关注点分离,即。构造函数不应该检查requiredService的状态,它只是把它传递下去。与回调相同。
  3. 如果您需要重置服务(删除外部if in)setRequiredService),你不需要改变构造器中的逻辑等。