I'm trying to get my head around DI. Am I doing it correctly for classes that follow DI pattern?
class Boo
{
public $title = 'Mr';
public $name = 'John';
protected $deps;
public function __construct($deps)
{
$this->deps = $deps;
}
public function methodBoo()
{
return 'Boo method '.$this->deps;
}
}
class Foo
{
private $objects;
public function __construct()
{
}
// Set the inaccessible property magically.
public function __set($name, $value)
{
$this->$name = $value;
}
// Set the inaccessible $class magically.
public function __get($class)
{
if(isset($this->objects[$class]))
{
return $this->objects[$class];
}
return $this->objects[$class] = new $class($this->deps);
}
public function methodFoo()
{
return $this->Boo->methodBoo();
}
}
$Foo = new Foo();
$Foo->deps = 'says hello';
var_dump($Foo->methodFoo());
result,
string 'Boo method says hello' (length=21)
I don't want to use construction injection in some cases because not all methods in Foo rely on the same injections. For instance,methodFoo()
in Foo
relies on Boo
only, while other methods rely on other classes/ injections.
Also, I don't want to use setter injection either because I might have to write lots of them in Foo
, like
setBoo() {}
setToo() {}
setLoo() {}
... and so on...
So I thought using the magic method __get
and __set
could save me from ending up writing a long list of them. With this, I only 'inject' the dependency when it is needed by a method in Foo
.
Is this correct way of doing it? I haven't done any test with an unit test before. Can this solution be tested?
Or any better solutions you have got?