I’m trying to figure out the best practices for dependency injection in PHP.
Question: Do I have to inject all dependencies of a subclass into the parent class? I use the terms ‘parent’ and ‘child’ in terms of a composition relationship.
My hesitation is because I find myself giving the parent class all kinds of dependencies so that it can just pass them down to dependent child classes.
Edit:
Below is a more concrete example of what I’m talking about. MyClassA does not need the database connection object or the logger. DoSomething does need these objects, however. What is the best way to get the database connection and logger to the DoSomething instance? I don’t want to use singleton objects or global objects for the sake of unit testing. Also, this example only uses to classes. What if there are 3 or 4 and the 3rd or 4th needs some object instance but the first 2 or 3 don’t? Does MyClassA just pass the object to the next, and so on?
class MyClassA {
protected $_doSomethingObject;
public function doSomething()
{
return $this->_doSomethingObject()->doSomethingElse();
}
public function setDoSomethingObject($doSomethingObject)
{
$this->_doSomethingObject = $doSomethingObject;
}
}
class DoSomething {
protected $_logger;
protected $_db;
public function doSomethingElse()
{
$this->_logger->info('Doing Something');
$result = $this->_db->getSomeDataById();
return $results;
}
public function setLogger($logger)
{
$this->_logger = $logger;
}
public function setDBConection($db)
{
$this->_db = $db;
}
}
Is the best way the example I show below? If so, then the best way is to work backwards so to speak…?
$logger = new Logger();
$db = new DBConnection();
$doSomething = new DoSomething();
$doSomething->setLogger($logger);
$doSomething->setDBConnection($db);
$a = new MyClassA();
$a->setDoSomething($doSomething);
Yes. As I mentioned in the comment, you set up the inner most objects first.
If an object create another object internally that isn’t exposed, then it could pass along its injected objects if appropriate. For example:
However, if that secret
Fooobject needed references to other things thatDoSomethingdidn’t have, then you’ve got design issues. If that happens you need to do whatever is appropriate:fooobject into the parent object prior to callingfoo().foo().