tl;dr of DI vs SL

Chris Hartjes has a nice writeup on dependency injection containers versus service locators. Here’s a short way to tell which one you’re using:

“If your class has a dependency on a container, you’re using Service Locator, not Dependency Injection.”

If you have a DI container and you pass it into a class so that class can get its own dependencies from that container, you are *still* doing Service Locator. It doesn’t matter that the locator is called a DI container. The key is that the object is pulling in its dependencies, instead of something outside of the object pushing the dependencies into it.

Are you stuck with a legacy PHP application? You should buy my book because it gives you a step-by-step guide to improving your codebase, all while keeping it running the whole time.

3 thoughts on “tl;dr of DI vs SL

  1. And what if you declare your dependencies in your PHPDoc, like @inject. And use reflection to automatically build / compile, a separate class, with dependencies, external data fetching ( and cleaning ) etc?

    Technically, the object is what is requesting the data ( indirectly using PHPdoc ), you can have more clean code, and a clean constructor.

    class a {
    * @inject database
    function a ( $sc, $a1, $a2, ... )

    Very easy to test, as you do not rely on any internal linked data.


    class a_a extends serviceController {
      public database;
      function __construct()
        // Do whatever needs to be done, to properly "feed" the dependencies of the function / class / ...

    And you can call your ” class/function”, using a closure… All compile with reflection ofcourse… And you can let APC cache all those DI configurations, as needed.

    Something i’m working on. Think that is pure Constructor DI, no mater how you twist and turn it. Despite getting it from a container. Anyway, what is in a name. People are a sometimes going overboard making things complex or giving themselves more code to deal with, to deal with standards that everybody fights over as to what is the correct implementation. *lol*

  2. Personally, I’m not a fan of DI-via-annotations. If you have two classes that use a “database” service, and then you want one (but not the other) to use something besides that “database” service, you have to modify the source code annotation.

Leave a Reply

Your email address will not be published. Required fields are marked *