I have two classes
ClassA , ClassB
Classes commonly depend upon two basic services and repositories
ServiceA , ServiceB
Classes (ClassA , ClassB
) use DI principle to inject dependency using constructor.
Since all three share a few common service as mentioned above I want to group all the common methods and services to a class Base
Like this
Base Class
class Base {
protected $A;
protected $B;
public function __construct(ServiceA $A, ServiceB $B){
$this->A = $A;
$this->B = $B;
}
}
Child Service
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);
}
}
Question
How can I have common parent dependency without breaking IoC principles?
Possible Case 1
I know I have to call parent::__construct()
to initialize Base constructor. But then I have to define Parent's dependency in all child class like below.
(But for large number of child I have to repeat this process. It defeats purpose of having common DI point).
class Child extends Base {
protected $C;
public function __construct(ChildDependency $C, ParentDepen $A, ParentDepn $B){
parent::_contruct($A,$B);
$this->C = $C;
}
}
Possible Case 2
Having use Getter and Setter. But I think they break the IoC principle.