Professional PHP

PHP Programming, Web Development, PHP Advocacy and PHP Best Practices.
« Programming Language Trends via Google
un-PEAR-ing »

Dependency Injection in PHP

June 26th, 2006

The June issue of PHP Architect is out. My column this month is on dependency injection, a topic which I’ve been warming up to lately.

First there was CORBA. Then insane complexity of CORBA was supplanted by the intolerable complexity of EJB. Influenced by an agile mindset and the power of Unit testing, a group of java programmers began to construct simpler alternatives to EJB. Thus, the inversion of control frameworks were born. Martin Fowler came along, clarified and renamed the pattern dependency injection. This activity has originated in the Java world, but the pattern applies in PHP as well.

It is heartening to see an industry solve a problem over the course of a decade, moving from complex vendor driven middle-ware to simple patterns. The thing I like most about DI is how dead simple it really is.

Fowler’s article is a must read on the topic. However, I have two problems with most of the introductions to dependency injection. One is the use of irrelevant girl kisses boy style examples. The other is the over-emphasis on the container. The whole point of dependency injection is to move away from invasive component architectures, such as EJB. From my point of view, it is far more interesting to explore what impact dependency injection has on your design than what features your container has.

With that in mind, I tried to write an introduction to dependency injection that avoiding talking about DI containers and that tried to use real, relevant examples. For an example, I started with a typical, run of the mill dependency, torn from a popular PHP library that shall remain nameless, but easy to guess. Then I build on that with a plug-able backend in a common PHP style and then again using dependency injection.

For me dependency injection is relatively new territory, but one that I feel is an important technique. I’d like to see this technique become more widespread in PHP, especially in the current crop of frameworks.

I have a significant bias, but I think you should read the article. I hope you find it useful.

Filed Under

  • Agile Methods, PHP, Software Design

Related Posts

  • Documentation versus Productivity?
  • php|tek Slides
  • php | architect back issue bargains
  • ZendCon: Writing Maintainable PHP Code
  • Why isn’t PHP the natural successor to Java?
You can leave a response, or trackback from your own site.

25 Responses to “Dependency Injection in PHP”

  1. Hans L says:
    6/27/2006 at 5:12 am

    (I don’t have access to the above-mentioned article, so I may be speaking at cross points or out of turn here.)

    I was really interested to see this topic, as I had also been thinking about DI in PHP a lot lately. I have read the Fowler article in the past (just glanced over it again), and have some practical experience with Spring (and a bit of HiveMind) in Java. I like DI for the simplicity it brings to unit testing — by removing the dependency on some central service locator. While I think PHP could benefit from that aspect of DI, I keep running into the question of how DI would work in a way that would scale / perform decently in PHP.

    PEAR and PEAR-style classes are replete with the factory-driven object instantiation which lends itself to a simple service locator approach (e.g. Horde loads config values and then calls factory() methods with driver names & params). This approach is a bit API limiting & encourages the use of associative arrays to pass params (which is bug-prone) but the advantage here is that the service locators only lookup & instantiate classes on demand. If I were using a Spring-style DI solution to wire up all of my objects, I’d have many, many more objects being instantiated than I would actually need to use for a given request.

    So … I guess the question is what a lazy-loading DI solution would look like — and how different that would end up looking than a more “traditional” PHP service locator.

    -Hans

  2. Paul M. Jones » Blog Archive » Dependency Injection in Solar says:
    6/27/2006 at 5:24 am

    [...] Jeff Moore talks about dependency injection in PHP and opines as to how he’d like to see “the current crop of frameworks” adopt the technique. Jeff, your wish is granted! (At least for Solar. ;-) [...]

  3. PHPDeveloper.org says:
    6/27/2006 at 5:26 am

    Jeff Moore’s Blog: Dependency Injection in PHP

  4. Jeff says:
    6/27/2006 at 4:18 pm

    Hans,

    I think the default in spring is for the container to instantiate objects when the container is loaded. Obviously, that would be a terrible idea in PHP. However, there is no reason why the container can’t first be loaded with the information on how to instantiate the objects. Then, when an object is retrieved from the container, it and all of its dependencies can be instantiated as needed.

    The more perplexing issue here is conditional dependencies. That can be done by passing a lazy loading proxy objects, with the knowledge that there are certain limitations in PHP to what these kinds of objects can do. (Creating an __implements magic method in PHP so an object can dynamically declare which interfaces it implements would go a long long way to better proxy objects.)

    However, as I said in my post and in the article, I don’t believe you need a container to gain from dependency injection. The same object should be able to be used with any container, and therefor, without a container. To me, the important part of DI is its impact on design.

    Regarding service locator, I don’t feel that’s a best practice. To me, its a half step into the world of DI. You’re still left with that big dependency on the service locator.

    See Spring XML configuration best practices and Dependency injection anti-patterns.

    As for a DI container in PHP, I’m waiting to see what happens with Marcus Baker’s Phemto project. I’m looking forward to seeing what he comes up with.

    DI containers in PHP do have to be implemented differently because of the per-request life-cycle. We’ve already been experimenting with lazy loading and DI in WACT for quite some time. here is our current implementation, with lazy loading.

    I already know that Marcus and I have slightly different ideas about what is needed for DI. I’m hoping that I’ll be able to contribute to Phemto and use it instead of what we did with WACT 0.2 without messing up Marcus’ intentions too much.

  5. Hans L says:
    6/28/2006 at 5:46 am

    Jeff,

    Very interesting. And I completely agree that __implements would make a *huge* difference in proxy objects in PHP. At that point they would be essentially seamless, since typehints, SPL Iterators (etc.), and instanceof would work again.

    What was really attractive to me about the Spring way of doing things was that the service objects themselves don’t need to have any knowledge of Spring. The dependency is truly “injected” — not “requested” or “located”. (And I think that Spring simply becomes a service locator when an app starts using the ApplicationContext to fetch beans.)

    I think I need to read the article, but I don’t see the difference between what you describe as DI in WACT and the service locator pattern as Fowler describes it. It’s perhaps a subtle difference, since service locators also remove direct dependencies.

    Anyway, thanks for the thought-provoking post. I’m gonna go get my company to renew our subscription to PHP|Architect :)

    Cheers,
    Hans

  6. Jeff says:
    6/28/2006 at 7:41 am

    Hans,

    The file I linked to is for PHP 4, so no proxies. Therefor, an object must be “factory protocol aware” aware if lazy loading is to be used. The object that receives the handle must dereference it to get at the real object by calling _CreateObject(). Since there are no parameters, its not really a ServiceLocator, as I would describe it. But, since the object has to be aware that it is receiving a proxy, its not strictly DI, either. If you don’t nest Handles, though, it is the DI pattern because the ObjectRegistry will dereference the first Handle for you. The Handle name in WACT is historic.

    I agree that the key aspect of DI is that the objects don’t need knowledge of their containers. In the PHP 5 version of WACT, I hope this will be true. (Actually, I hope to be able to use Phemto to make this true.)

    Cool news on the subscription. You also can also download the electronic copy of this month’s article for 3.49 USD, which isn’t too bad. There’s a lot of other good stuff in this issue, too — like instructions for setting up PHP debugging in eclipse. Anyway, I would be interested to hear your perspective on DI and the back-end driver architecture from the article.

  7. HOzawa says:
    7/9/2006 at 11:12 pm

    Hi all,
    You may be interested in PHP version of Seasar2, which is a DI Container
    with AOP.
    http://www.seasar.org/en/php5/index.html

    Cheers,
    H.Ozawa

  8. D.M says:
    9/9/2006 at 3:27 am

    Hi ..
    I just want to ask about COM object .
    To deal with this in PHP .. should I install OFFICE . or I can install just MS WORD COM for example from somewhere ?

    Thanks alot for your help

  9. Antonio Parraga says:
    6/16/2008 at 2:38 am

    A framework with a spring-style dependency injection: lionframework.
    Take a look at http://www.lionframework.org

    Regards
    Antonio

  10. John Paul de Guzman says:
    11/24/2008 at 2:26 am

    If you want a lightweight PHP IOC you want to take a look at:
    http://www.raincreativelab.com/dl/php_ioc/

    Thanks,
    JP de Guzman

  11. Five Tips To Make Good Object-Oriented Code Better | BrandonSavage.net says:
    10/27/2009 at 10:00 pm

    [...] Injection For the longest time I didn’t realize the importance of dependency injection. But dependency injection is critically important, especially if you want to write or utilize a framework or do any kind of [...]

  12. ash says:
    3/28/2010 at 11:09 am

    could you post your php architect here? Can’t find it on their site.

  13. ash says:
    3/28/2010 at 11:10 am

    *php architect article

  14. jessica says:
    6/27/2010 at 9:07 pm

    i always be reported the error when i run php

  15. rita says:
    6/27/2010 at 9:17 pm

    i use zencart, but often some code error

  16. Viannabor says:
    9/10/2010 at 5:20 am

    downloadable software online , buy software low cost

  17. Marcelo Gornstein says:
    2/4/2011 at 1:45 pm

    You might also want to try Ding (http://marcelog.github.com/Ding), since it shares the same need (to have/use a spring-alike framework for php). Supports some JSR annotations and implements most of the spring’s container features (and some more).

    In terms of performance, cache are used instead of php code, which results in faster execution as well.

    I hope you enjoy it as much as I enjoyed writing it

    Regards!

  18. uzamax says:
    3/6/2011 at 10:47 am

    %100 Do?al ve hiç bir yan etkisi olmayan Uzamax’? ke?fedin
    UZAMAX içeri?inde mineral ve vitaminler bar?nd?ran, do?al bitkielerden üretilmi? g?da deste?idir. ?çeri?inde herhangi bir kimyasal ürün bulunmamakla birlikte tamamen do?al kurutulmu? bitkisel bir kar???md?r. Sadece birkaç ayl?k kullan?m kürü sonras?nda bile uzamax’?n etkisini hissedeceksiniz.

    Uzamax kullanarak do?al yollarla bünyenize gerekli olan tüm besin, vitamin ve mineralleri vücudunuza alman?z? sa?lar.izlanda yosun hapi

  19. Sarah Plyer says:
    9/28/2011 at 1:10 pm

    Thank you, I’ve been hunting for details about this subject matter for ages and yours is the best I have located so far.

  20. Moira says:
    11/2/2011 at 5:33 pm

    It really is difficult to find familiar people on this subject matter, however you sound like you know what you are posting about! Regards

  21. Calista Arriaga says:
    1/5/2012 at 12:35 am

    Am I the only one who thinks your blog theme is fairly amazing? I’m guessing maybe its a custom theme that you bought? Regards, Pete.

  22. Vernetta Wallin says:
    1/10/2012 at 5:17 am

    hello there and thanks on your information ? I’ve certainly picked up something new from right here. I did however expertise some technical points using this web site, since I experienced to reload the site lots of times previous to I could get it to load correctly. I have been wondering in case your hosting is OK? Not that I’m complaining, but slow loading cases times will sometimes impact your placement in google and could injury your high-quality ranking if advertising and marketing with Adwords. Anyway I am including this RSS to my e-mail and could look out for a lot extra of your respective exciting content. Ensure that you update this once more soon..

  23. Levi Pezzullo says:
    1/11/2012 at 6:47 am

    I have ceded control of the Taurus 380 to the lovely wife. She didn’t like the extra weight of our Bersa Thunder 380 in her purse. She much prefers the light weight of the Taurus. We went to the range on 7/25/11 and, despite the increase in recoil, she felt comfortable shooting the little bugger. We burned another 50 Fiocchi 380’s for a total of 400 shots fired. We had a couple of FTE’s for the first time. The gun was filthy (not cleaned since I bought it in Feb. 2011). I cleaned and oiled it and expect that will fix the issue.

  24. Georgette says:
    1/22/2012 at 6:40 am

    Truly difficult to find informed individuals about this topic, but you sound like you understand exactly what you are preaching about! Cheers

  25. Jessenia Richwine says:
    1/31/2012 at 9:29 pm

    Thanks for your ideas.Hope this will work for me in the time to come. It was easy reading this post ! Good article

Leave a Reply

Click here to cancel reply.

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

code: use [code=php][/code].

Comment Preview

    Subscribe Feed
    Share Subscribe to this blog…
    Share Bookmark or share this page…
  • About

    My name is Jeff Moore. I'm a PHP programmer living in San Francico and working for a startup.

    More about me…

  • Categories (Home)

    • Agile Methods (14)
    • Mac (14)
    • Misc (18)
    • Open Source (14)
    • PHP (99)
    • Software Design (29)
    • Usability (14)
    • Web Design (20)
  • Recent Comments

    • The Legality of Republishing RSS Feeds  28
      Tory Rennemeyer, eenicker, Reverse Phone Lookup [...]
    • Working with PHP 5 in Mac OS X 10.5 (Leopard)  258
      Tuan Lal, Lavagem de estofados, Edward L. Kind [...]
    • php | tek 2008  36
      how to mend ice machine, Akademija Debelih, Odbacena [...]
    • goto in PHP  59
      kasor, Thomas Valdivieso, Murray Ziadie [...]
    • Firefox Extensions for Web Developers  33
      kasor, Website Design Toronto, mobila bistrita [...]
    • Why PHP is easier to learn than Java  68
      kasor, Justina Calvery, Guy Lipton [...]
    • Meta Tag Refresh Faux Paux  43
      html email templates, E-Juice Reviews, image [...]
    • Improved Error Messages in PHP 5  49
      Carroll Tina, Przeprowadzka, Emery Harari [...]
    • Benchmarking PHP's Magic Methods  33
      kayu oyunlar?,dora,oyun,oyna, Benjamin Bejjani, paypal website [...]
    • Microbenchmarks of single and double qouting.  24
      kefir grains minneapolis, sexshop dildo, tuim688 [...]
  • Recent Posts

    • Richard Thomas
    • ZendCon: Writing Maintainable PHP Code
    • Looking Towards the Cloud
    • Holiday Tech Support
    • Closures are coming to PHP
    • php | tek Wrapup
    • php | tek 2008
    • Sarah Snow Stever
    • Benchmarking PHP’s Magic Methods
    • The Endpoints of the Scale of Stupidity on Video
  • Site

    • Archives
    • Log in
  • Search