For dependency injection, I understand that I need to transfer an instance of one class to the main instance instead of the main class, creating its own instance, for example (php):
class Class_One { protected $_other; public function setOtherClass( An_Interface $other_class ) { $this->_other_class = $other_class; } public function doWhateverYouHaveToDoWithTheOtherClass() { $this->_other_class->doYourThing(); } } interface An_Interface { public function doYourThing(); } class Class_Two implements An_Interface { public function doYourThing() { } } class Class_Three implements An_Interface { public function doYourThing() { } }
Everything is good. I know that since both the Class_Two and Class_Three classes implement An_Interface, they can be used interchangeably in Class_One. Class_One would not know the difference between the two.
My question is, is it ever better to use an instance for setOtherClass, pass a string like "Class_Two", and the Class_One setOtherClass method actually creates the instance itself like this:
class Class_One { ... public function setOtherClass( $other_class_name ) { $this->_other_class = new $other_class_name(); } ... }
Is such a defeat of the goal of the Injection of Dependence, or is it completely true? I thought this type of customization could help me with customization where the user can specify which class he wants to use in the string earlier, and this can be passed to Class_One later ..
Actually, having written this, I thought that this is probably not a very good solution, but I will post it anyway if someone can give me good feedback on why I should / should not do this.
Thanks =)
Ryan
source share