Page 1 of 1
Dependency Injection
Posted: Fri Sep 14, 2007 4:23 am
by Chris Corbyn
I'd always assumed DI was some really complex design pattern, yet it appears I've been using DI without even knowing it, unless I'm missing something.
Apologies for the link to a Java article, it just happens to be what I was reading:
http://www.javaranch.com/journal/200709 ... 709.jsp#a4
Is that seriously all there is to it? Injecting objects which implement an interface via a setter method? I could have sworn I'd seen more complicated demonstrations of it than that. Hmm...
Posted: Fri Sep 14, 2007 5:46 am
by timvw
Passing in the "dependency" itself in the constructor is only *one* of many ways to Inject dependencies
(eg: If you passed in a ResourceLocator in the constructor you would immediately be able to get all dependencies when you need them...)
And then the fun begins with Spring Injection etc because they provide whole libraries to not only inject dependencies, but also load factories that are able to create the actual objects (on which the consumers depend))...
Anyway, as i already mentionned, an article summing up a couple of solutions to solve the problem:
http://martinfowler.com/articles/injection.html
Posted: Fri Sep 14, 2007 5:53 am
by Chris Corbyn
timvw wrote:Passing in the "dependency" itself in the constructor is only *one* of many ways to Inject dependencies
(eg: If you passed in a ResourceLocator in the constructor you would immediately be able to get all dependencies when you need them...)
Hmm... I'll have to look into this again then

Everybody does talk about the spring framework (or Phemto in PHP) when they refer to DI. Neither of those am I familiar with.
Posted: Fri Sep 14, 2007 6:04 am
by Chris Corbyn
Ah ha, I got it. I was thinking factory classes would be a good way to implement DI. Looking at a Spring configuration excerpt you see this:
Code: Select all
<beans>
<bean id="AirlineAgency" class="com.dnene.ditutorial.common.impl.SimpleAirlineAgency" singleton="true"/>
<bean id="CabAgency" class="com.dnene.ditutorial.common.impl.SetterBasedCabAgency" singleton="true">
<property name="airlineAgency">
<ref bean="AirlineAgency"/>
</property>
</bean>
<bean id="TripPlanner" class="com.dnene.ditutorial.common.impl.SetterBasedTripPlanner" singleton="true">
<property name="airlineAgency">
<ref bean="AirlineAgency"/>
</property>
<property name="cabAgency">
<ref bean="CabAgency"/>
</property>
</bean>
</beans>
So basically the dependencies are listed in XML and I can jump to a fairly confident conclusion that they have some generic factory which glues everything together. Pretty neat I guess

Posted: Fri Sep 14, 2007 6:10 am
by Maugrim_The_Reaper
Have a look at Pico Container. There's a PHP implementation available.
Posted: Fri Sep 14, 2007 6:19 am
by timvw
It's pretty neat, but use it with sense.. Otherwise you'll experience "Great Pain(tm)" when you transition from DVL to TST/QUA/PRD and have to figure out where you injected mocks...
