tl;dr of DI vs SL

By | June 7, 2012

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.

3 thoughts on “tl;dr of DI vs SL

  1. Drew

    +1 for referring to it as a “DI container” instead of a “DIC”

    Reply
  2. Ben

    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, ... )
    {
      $sc->database->query...
    }
    }

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

    File2:

    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*

    Reply
  3. pmjones Post author

    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.

    Reply

Leave a Reply

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