在类之间共享依赖关系,同时允许依赖注入

Sus*_*ant 5 php oop laravel php-5.5

我有两节课

ClassA , ClassB
Run Code Online (Sandbox Code Playgroud)

类通常依赖于两个基本服务和存储库

ServiceA , ServiceB
Run Code Online (Sandbox Code Playgroud)

类 ( ClassA , ClassB) 使用 DI 原理通过构造函数注入依赖。

由于这三个共享一些公共服务,如上所述,我想将所有公共方法和服务分组到一个类中,Base如下所示

基类

class Base {

    protected $A;
    protected $B;

    public function __construct(ServiceA $A, ServiceB $B){
       $this->A = $A;
       $this->B = $B;
    }
}
Run Code Online (Sandbox Code Playgroud)

儿童服务

class Child extends Base {

    protected $C;        

    public function __construct(ChildDependency $C){
       $this->C = $C;
    }

    public function doStuff()
    {
         //access the $A (**Its null**)
         var_dump($this->A);
    }

}
Run Code Online (Sandbox Code Playgroud)

问题

如何在不违反 IoC 原则的情况下拥有共同的父级依赖关系?

可能的情况1

我知道我必须调用parent::__construct()来初始化 Base 构造函数。但是我必须在所有子类中定义父类的依赖关系,如下所示。

(但是对于大量的孩子,我必须重复这个过程。它违背了拥有共同 DI 点的目的)。

class Child extends Base {

    protected $C;        

    public function __construct(ChildDependency $C, ParentDepen $A, ParentDepn $B){
       parent::_contruct($A,$B);
       $this->C = $C;
    }
}
Run Code Online (Sandbox Code Playgroud)

可能的情况2

已经使用了Getter和Setter。但我认为他们违反了国际奥委会原则。

Der*_*rek 4

如果您必须从创建对象的任何内容中注入依赖项,这似乎是您最好的选择:

class Child extends Base {

    protected $C;        

    public function __construct(ServiceA $A, ServiceB $B, ChildDependency $C){
       parent::__contruct($A, $B);
       $this->C = $C;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以尝试使用Traits代替:

trait ServiceATrait {
    public $A = new ServiceA();
    public function getServiceA() { return $this->A; }
}
trait ServiceBTrait {
    public $B = new ServiceB();
    public function getServiceB() { return $this->B; }
}
class Base {
    use ServiceATrait;
    use ServiceBTrait;
}
class Child extends Base {
    protected $C;        

    public function __construct(ChildDependency $C) {
       $this->C = $C;
    }
}

function() {
    $c = new Child(new ChildDependency());
    echo $c->getServiceB()->toString();
}
Run Code Online (Sandbox Code Playgroud)