Try Tuts+ Premium, Get Cash Back!
Dependency Injection: Huh?

Dependency Injection: Huh?

Tutorial Details
  • Difficulty: Intermediate
  • Completion Time: 15 Minutes

Chances are, at some point in your learning, you’ve come across the term, “dependency injection.” If you’re still relatively early in your learning, you likely formed a confused expression and skipped over that part. Still, this is an important aspect of writing maintainable (and testable) code. In this article, I’ll explain it in as simple a way as I’m capable of.


An Example

Let’s jump into a fairly generic piece of code, and discuss its short-comings.

class Photo {
	/**
	 * @var PDO The connection to the database
	 */
	protected $db;

	/**
	 * Construct.
	 */
	public function __construct()
	{
		$this->db = DB::getInstance();
	}
}

At first glance, this code might seem fairly harmless. But consider the fact that, already, we’ve hardcoded a dependency: the database connection. What if we want to introduce a different persistence layer? Or, think about it this way: why should the Photo object be communicating with outside sources? Doesn’t that violate the concept of separation of concerns? It certainly does. This object shouldn’t be concerned with anything that isn’t directly related to a Photo.

The basic idea is that your classes should be responsible for one thing only. With that in mind, it shouldn’t be responsible for connecting to databases and other things of that nature.

Think of objects in the same way that you think of your pet. The dog doesn’t decide when he goes outside for a walk or to play at the park. You do! It’s not his place to make these decisions.

Let’s regain control of the class, and, instead, pass in the database connection. There are two ways to accomplish this: constructor and setter injection, respectively. Here’s examples of both:

Constructor Injection

class Photo {
	/**
	 * @var PDO The connection to the database
	 */
	protected $db;

	/**
	 * Construct.
	 * @param PDO $db_conn The database connection
	 */
	public function __construct($dbConn)
	{
		$this->db = $dbConn;
	}
}

$photo = new Photo($dbConn);

Above, we’re injecting all required dependencies, when the class’s constructor method runs, rather than hardcoding them directly into the class.

Setter Injection

class Photo {
	/**
	 * @var PDO The connection to the database
	 */
	protected $db;

	public function __construct() {}

	/**
	 * Sets the database connection
	 * @param PDO $dbConn The connection to the database.
	 */
	public function setDB($dbConn)
	{
		$this->db = $dbConn;
	}
}

$photo = new Photo;
$photo->setDB($dbConn);

With this simple change, the class is no longer dependent upon any specific connection. The outside system retains complete control, as should be the case. While it may not be immediately visible, this technique also makes the class considerably easier to test, as we can now mock the database, when calling the setDB method.

Even better, if we later decide to use a different form of persistence, thanks to dependency injection, it’s a cinch.

“Dependency Injection is where components are given their dependencies through their constructors, methods, or directly into fields.”


The Rub

There’s one problem with using setter injection in this way: it makes the class considerably more difficult to work with. The user now must be fully aware of the class’s dependencies, and must remember to set them, accordingly. Consider, down the line, when our fictional class requires a couple more dependencies. Well, following the rules of the dependency injection pattern, we’d have to do:

$photo = new Photo;
$photo->setDB($dbConn);
$photo->setConfig($config);
$photo->setResponse($response);

Yikes; the class may be more modular, but we’ve also piled on confusion and complexity. Before, the user could simply create a new instance of Photo, but, now, he has to remember to set all of these dependencies. What a pain!


The Solution

The solution to this dilemma is to create a container class that will handle the brunt of the work for us. If you’ve ever come across the term, “Inversion of Control (IoC),” now you know what they’re referring to.

Definition: In software engineering, Inversion of Control (IoC) is an object-oriented programming practice where the object coupling is bound at run time by an assembler object and is typically not known at compile time using static analysis.

This class will store a registry of all the dependencies for our project. Each key will have an associated lambda function that instantiates the associated class.

There are a couple ways to tackle this. We could be explicit, and store methods, such as newPhoto:

// Also frequently called "Container"
class IoC {
	/**
	 * @var PDO The connection to the database
	 */
	protected $db;

	/**
	 * Create a new instance of Photo and set dependencies.
	 */
	public static newPhoto()
	{
		$photo = new Photo;
		$photo->setDB(static::$db);
		// $photo->setConfig();
		// $photo->setResponse();

		return $photo;
	}
}

$photo = IoC::newPhoto();

Now, $photo will be equal to a new instance of the Photo class, with all of the required dependencies set. This way, the user doesn’t have to remember to set these dependencies manually; he simply calls the newPhoto method.

The second option, rather than creating a new method for each class instantiation, is to write a generic registry container, like so:

class IoC {
	/**
	 * @var PDO The connection to the database
	 */
	protected static $registry = array();

	/**
	 * Add a new resolver to the registry array.
	 * @param  string $name The id
	 * @param  object $resolve Closure that creates instance
	 * @return void
	 */
	public static function register($name, Closure $resolve)
	{
		static::$registry[$name] = $resolve;
	}

	/**
	 * Create the instance
	 * @param  string $name The id
	 * @return mixed
	 */
	public static function resolve($name)
	{
		if ( static::registered($name) )
		{
			$name = static::$registry[$name];
			return $name();
		}

		throw new Exception('Nothing registered with that name, fool.');
	}

	/**
	 * Determine whether the id is registered
	 * @param  string $name The id
	 * @return bool Whether to id exists or not
	 */
	public static function registered($name)
	{
		return array_key_exists($name, static::$registry);
	}
}

Don’t let this code scare you; it’s really very simple. When the user calls the IoC::register method, they’re adding an id, such as photo, and its associated resolver, which is just a lambda that creates the instance and sets any necessary dependencies on the class.

Now, we can register and resolve dependencies through the IoC class, like this:

// Add `photo` to the registry array, along with a resolver
IoC::register('photo', function() {
	$photo = new Photo;
	$photo->setDB('...');
	$photo->setConfig('...');

	return $photo;
});

// Fetch new photo instance with dependencies set
$photo = IoC::resolve('photo');

So, we can observe that, with this pattern, we’re not manually instantiating the class. Instead, we register it with the IoC container, and then request a specific instance. This reduces the complexity that we introduced, when we stripped the hardcoded dependencies out of the class.

// Before
$photo = new Photo;

// After
$photo = IoC::resolve('photo');

Virtually the same number of characters, but, now, the class is significantly more flexible and testable. In real-world usage, you’d likely want to extend this class to allow for the creation of singletons as well.


Embracing Magic Methods

If we want to reduce the length of the IoC class even further, we can take advantage of magic methods – namely __set() and __get(), which will be triggered if the user calls a method that does not exist in the class.

class IoC {
	protected $registry = array();

	public function __set($name, $resolver)
	{
		$this->registry[$name] = $resolver;
	}

	public function __get($name)
	{
		return $this->registry[$name]();
	}
}

Popularized by Fabien Potencier, this is a super-minimal implementation – but it’ll work. Whether or not __get() or set() runs will be dependent upon whether the user is setting a value or not.

Basic usage would be:

$c = new IoC;
$c->mailer = function() {
  $m = new Mailer;
  // create new instance of mailer
  // set creds, etc.
  
  return $m;
};

// Fetch, boy
$mailer = $c->mailer; // mailer instance

Thanks for reading!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.makemescript.nl Maik Diepenbroek

    Thanks Jeff for another tutorial.

    As a software engineering student i often heard of IoC and dependency injection. But not in the extend explained by you. And certainly not in PHP. Now i know the language doesn’t really matter but as i’m most familiar with PHP i’m glad you did this in a language where IoC and di are not so well practiced by most.

  • Michael

    This method of coding makes everything so, so much easier down the road. Definitely helps you think and use object-oriented design too.

    I’ve made my own container and would be interested in peoples’ thoughts. It uses annotations to do auto-wiring too! Check it at https://github.com/mikesir87/PHP-Container

    • http://marco-pivetta.com/ Marco Pivetta

      Very interesting approach :) Looks like J2EE’s CDI. I like it!
      There’s some approaches I’ve also tried to use in ZF2, but I’d avoid some things such as making the container a singleton and implementing your own annotations.
      I’d drop the “ResourceInfoSet” and “ResourceInfo” and keep those in the container itself (after all, they’re just named instances, no?).
      ClassInfo and ClassInfoSet look like https://github.com/zendframework/zf2/blob/master/library/Zend/Di/Definition/ClassDefinition.php and https://github.com/zendframework/zf2/blob/master/library/Zend/Di/DefinitionList.php, which are basically class metadata.

      The concept is great, but consider reading about the classes I’ve linked below (Pimple, Zend\Di, Symfony\DependencyInjection), you can find a lot of inspiration there :)

      • Michael

        Thanks for looking at the code and for your thoughts! I actually did pattern a lot of it after the J2EE approach, since that’s what I’ve been doing a lot of at work. I’ll take a look at your suggestions and see how it can be improved!

  • Ian

    Nice Jeffrey,

    This is definitely something that fits into the small self learning projects I’ve been doing at home lately.

    I have one question. From some articles that are a couple of years old, benchmarking magic methods I came to the conclusion that a developer should only use them in specific situations like your Ioc example because they are slower than using regular setter and getter methods. Same situation with __call and __callStatic .

    I plan on doing my own benchmark tests but was wondering have they improved in more recent versions of php? Should we still be careful not to use them too much? Consider using them sparingly?

    Thanks

  • Amit Erandole

    Truly exceptional article. I once read the creator of Symfony framework try and explain dependency injection. He did not break through the concept for me but you did Jeffery.

  • Dex Barrett

    Thanks, Jeffrey. Just today I was reading about this topic and this article has been very helpful. I’m writing a small library in PHP to manipulate images and I wanted to implement some functions in the form of plugins because i didn’t want to populate the core files with the extra functionality. This along with autoloaders is gonna come in handy.

  • Thiago A.

    The IoC pattern considerably reduces the usage of static methods, but imposes a bit of a problem when you want to do so. Suppose your class needs to “strip garbabe” from a string, and that point of knowledge is statically located in Text::strip_garbage. What should I do here? Turn my Text static class helper into a singleton object? The problem is, I use some frameworks whose helpers are just static methods.

    • http://ocramius.github.com/ Marco Pivetta

      Well, yes, if you need to swap the pattern used, you’ll need to either remove that staticness or wrap it around an object that hides it behind a non-static method. IOC is not an absolute, it becomes handy when you need to actually have swappable logic.

  • http://ocramius.github.com/ Marco Pivetta

    Very nice article!

    You may also cite some relevant DIC/IOC containers, like Pimple ( https://github.com/fabpot/Pimple ), Zend\Di ( https://github.com/ralphschindler/Zend_DI-Examples ) and Symfony DIC ( https://github.com/symfony/symfony/tree/master/src/Symfony/Component/DependencyInjection ).

    If you want to patch your example to make it a bit more verbose (I think magic methods always add some more complexity and make things just more confusing) I wrote a DIC 101 at https://gist.github.com/3151903 :)

    Good job!

    • http://ajmichels.com AJ Michels

      Another issue with the magic methods is that it is much harder to code to a “contract”. You lose the ability to use type hinting which is another very powerful and under used feature.

      I have tried Symfony DIC and found the syntax and implementation to be well thought out. The biggest issue I had with it is that it was not trivial to introduce into an existing code structure.

      I am working on a PHP port of ColdSpring (http://coldspringframework.org) which is a DI and AOP application framework based on the Spring framework for Java. The default “factory” is very configuration heavy but I hope to write a different factory which will be more convention base. (http://git.ajmichels.com/?p=phpSpring;a=summary)

  • http://brayanrastelli.com Brayan Rastelli

    Nice tutorial.

    I was a bit confused on what the hell the IoC of Laravel does, but now I understand the concept.

    Will you cover it on your Laravel Essentials course?

    Thanks.

  • Kyle
  • http://www.antsmagazine.com/ Unaiz

    Awesome tut.. keep it up//

  • Frank de Jonge

    You’ve got an itsy bitsy error, accessing static::$db while it’s not declared as static ;-)

  • Ionutab

    For further reading please enjoy: http://martinfowler.com/articles/injection.html

  • Boabramah Ernest

    THE HOLY CONTAINER – speaking

    That shall avoid the use of new keyword in classes.

    namespace Authenticate;

    Auth{

    private $user;

    function __constructor()
    {
    $this->user = new \Model\User();

    //… more code
    }
    }

    That shall use only the container for the management of dependencies.

    $container->set(‘auth’, function() {
    return Authenticate\Auth();
    });

    That shall keep the container out of reach from Classes.

    $container->set(‘auth’, function($container) {
    $auth = Authenticate\Auth($container->get(‘user’));
    $auth->setUser($container->getParam(‘user’));
    $auth->setPassword($container->getParam(‘password’));
    return $auth;
    });

    and remember to refactor your class when it depends on many objects.

    programmer – speaking

    Ok holy container what sin have I committed if I passing the whole container to the class?

    $container->set(‘auth’, function($container) {
    return new Authenticate\Auth($container);
    });

    And later do

    namespace Authenticate;

    Auth{

    private $user;

    function __constructor($container)
    {
    $this->user = $container->get(‘user’);

    //… more code
    }
    }

    THE HOLY CONTAINER – speaking

    My Dependency Injection fundamentalist or extremist say you should be sentence to prison and be force to subscribe to nettute premium but do not worry for I holy container will get you there when you need me.

    My worry is that my fundamentalist will propose your immediate execution should you write the code below.

    Auth{

    private $container;

    function __constructor($container)
    {
    $this->container = $container;

    //… more code
    }
    }

    • http://ocramius.github.com/ Marco Pivetta

      Not just the fundamentalist, also the guy who will have to test and mock your stuff ;)

  • http://www.maikeldaloo.com Maikel D

    Thanks for the great explanation.

    Well done Jeff.

  • http://www.shiftedwork.de/blog Daniel S

    I really like the post picture!
    Your example IoC Container is a very basic one but should explain this stuff for oop newcomers..

  • http://www.insign.ch Martin Bachmann

    Great introduction, thanks! It might be worth mentioning that the FLOW3 php framework (http://flow3.typo3.org/ – the foundation of the new Typo3 Phoenix cms) is heavily using DI and IoC concepts.

  • http://twitter.com/haz_bo Harry

    Very nice article, I’ve recently been using Pimple which has been great. I also wrote my own just a couple of days ago:

    https://github.com/harry-lawrence/community

  • http://www.xcellence-it.com Xcellence IT

    Great article. This is what makes a real difference between a pro & other developers. We strongly follow this approach for all our projects and the benefits are enormous in terms of reliability and maintenance.

  • Umair

    Very well explained!

  • http://www.squidoo.com/this-is-bucharest Bucarest

    This is an exceptional explanation of di, and the layout of the article makes it easy to follow along.

  • Ed

    Thank you Jeff!

    Great article!

  • http://ajmichels.com AJ Michels

    Thanks for covering this topic. Working with Java developers so much I have often had to defend PHP has a viable enterprise platform. It makes it much easier to do so when I can point to these types of examples as evidence that not all PHP code should be served with marinara and meatballs.

    • http://inkwell.dotink.org Matthew J. Sahagian

      Have you thought about defending it by pointing out that PHP developers still have a will to live because they can be creative and have fun rather than being psychotically anal about code that more than likely will never be seen or used by anyone outside the chain of “engineers” slowly marching through their companies HR department, CS degree in hand, thinking they’ll save the world via namespacing?

      Viable enterprise platforms only work insofar as they have viable human beings to build and support them.

      Everyone name the most boring app they’ve ever used. Guaranteed it’s written in Java!

      • http://www.jeffrey-way.com Jeffrey Way
        Author

        Oh there’s certainly validity in that argument. It’s not for all projects.

  • Revathi

    Very Nice

  • robb

    “Think of objects in the same way that you think of your pet. The dog doesn’t decide when he goes outside for a walk or to play at the park. You do! It’s not his place to make these decisions.”

    Clearly, you’ve never owned a dog :)

    Good article.

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Haha – I have, in fact. But, I agree with you. They decide. :)

      • Alchemication

        Hehe, and don’t disregard cats please!!!

  • http://inkwell.dotink.org Matthew J. Sahagian

    Dependency Injection is not a technical issue in PHP:

    http://scriptogr.am/mattsah/post/dependencies-in-php

    It’s a developer mental issue.

    • Wilson

      It’s a great article. Thanks Matthew J. Sahagian.

  • Zdenek Sotolar

    Hi,
    you can read a great article explaining Dependency Injection with Nette Framework.

    http://doc.nette.org/en/dependency-injection

  • David D’hont

    I agree with Matthew for the most part.

    And, maybe Dependency Injection is so uncommon because when I see an article like this, it makes my brain hurt.

  • aditya ingle

    Nice tutorial. you exaplain the concept in easy language. like it thank you. i will be happy if you publish more tutorials on design patterns.

  • http://markstar.co.uk Mark Starling

    Hi Jeff,

    I was with you on the post until you started talking about the IoC container – I would normally solve this issue using the Factory pattern (which, is very similar). Can you explain the differences between the two and why you settled on this approach?

    Cheers.

  • Kristiaan Van den Eynde

    For those interested:
    - Larry Garfield (Crell) spoke on this and much more at DrupalCon Munich in his session “Functional PHP”.
    - Fabien Potencier was also there and gave a very interesting keynote two days later.

    http://munich2012.drupal.org/program/sessions/functional-php
    http://munich2012.drupal.org/speakers/keynotes/fabien-potencier

  • mpmedia

    Nice article , and again :

    http://pimple.sensiolabs.org

    ;) , pimple is simple enough to be used by everyone even beginers , it is a IOC container , with lazy loading ,etc …
    Jeff you should check the Silex framework too , it’s really nice , i’m building an demo app right now to sell the tech to my boss ( my app is not finished yet though) : https://github.com/Mparaiso/Silex-Blog-App
    cheers !

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Will do!

  • http://www.frompsdtowordpress.com Adz

    Great article, its nice to see more about Dependency Injection.

    As a complimentary addition to this article and links already provided within the comments, readers might also like the following from potstuck.com;

    http://www.potstuck.com/2009/01/08/php-dependency-injection/
    http://www.potstuck.com/2010/09/09/php-dependency-a-php-dependency-injection-framework/
    https://github.com/ryanto/PHP-Dependency

    To help further their understanding.

    Keep up the good work Jeff, always appreciated!

  • alireza

    Hi jeffrey. Thanks.

  • Sawny

    What a bad example.

    public function __construct()
    {
    $this->db = DB::getInstance();
    }

    With this code I could easily change DB, just edit some values at the DB::getInstance() function.
    And now you’r whole tutorial lost it’s meaning: explain __WHY__ I want to use dependency injections.

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Much better to inject the connection.

      • Sawny

        But __WHY__?

        With DI I need to write more code that does nothing extra as I see it.

        Convince me.

      • Mitchell

        With a smaller application you don’t need to use Dependency Injection, you don’t need to use it at all. But.. When you start creating bigger applications, setting more dependenies, etc etc. You’ll start to get unstructured code very fast. At some point you will start hacking in your own code and when you hit that milestone it’s hard to fix your code easily.

        But again, you don’t need to use it. But again again, i recommend you do.

      • http://www.jeffrey-way.com Jeffrey Way
        Author

        Once you start testing your code, you’ll begin to understand how dependency injection can be a benefit.

  • Luc

    Jeffrey maybe you will do a tutorial on Tuts+ on how to make a secure website. It’s a very sensible topic.

  • Zay

    Thanks Jeffrey.

    I would be nice to see series of tutorials like

    - dissecting Laravel framework
    - 10 Things I learn from Laravel framework.

  • Angelo

    Uhh, the “But what if you want to want to change your app to use a different DBMS?” argument. Seriously, that never happens, not in apps that are even remotely well spec’d out. It’s like seeing Bigfoot. Everyone knows about him but the only people who actually claim to have seen him turn out to be liars, drunks or idiots.

    If you KNOW you’ll be supporting various this or thats then great, use DI. But this whole mentality that DI needs to be used everywhere because “newing” up anything is horrible is just plain idiocy.

    DI is not some holy grail, nor is it free. It has downsides like nearly every design pattern. DI kinda sucks without IoC as you mentioned and even with it, it can make code less intuitive and difficult to read and follow, especially when you toss in a heavily abstracted object model. This might not matter in your 4 man startup, working on 10k lines of code but in any system of significant size or complexity, code readability is paramount. Consider that for the vast majority of medium to large businesses, by far the biggest cost is employees and you start to see why wasting time with overly complicated code that takes longer to maintain is retarded.

    Use the right tool for the job. When that tool is no longer the right one for what you’re doing, toss it. Don’t force square pegs into round holes for “consistency” or hypothetical flexibility that you’ll never need.

    If you actually do need to make use of your super flexible, super loosely coupled code to make some radical change, chances are, you still spent far more time creating and maintaining the complex design than it saves you in ease of implementing your new functionality.

    Any complexity you add costs you time and money for the life of the application. If you don’t need it now or don’t know for a fact that you’ll need it in the near future, DON’T CODE IT. In other words, don’t make it till you need it.

    • mpmedia

      Nobody forces anybody to use DI , TDD , BDD , IoC containers , Metaprogramming , AOP , and even OOP;
      Like nobody forces anybody to model an application using Model driven Dev or Domain Driven Dev , or UML or Entity Relation for RDBMS , or to use Agile or Scrum or XP. However , it is easier to communicate with other developpers in a team if a method is implemented and standardized across all the people that are part of the team. That’s what all these techniques are for , because they have been used and work, and make developers lifes easier.

      “Any complexity you add costs you time and money”

      Complexe problems require complexe solutions ,there is no escape. As your code base grows , how do you deal with these issues without using proven techniques ? this techniques are like an investment, it cost a bit of time but saves you a lot on the long run. The knowledge is free , why not learn ?

  • 100asa

    So let’s say I have a init.php file that takes care of all initializing for my script. Should I register all of the dependencies in there?

  • http://www.2lessons.info/ 2lessons

    Thanks Jeff for this great tutorial.

    I’m working with PHP since last 1 year. But never thought about Dependency Injection. This was certainly helpful.

  • http://imperativedesign.net Paul

    Hey Jeff,
    Im a bit lost by your implementation and its simplification.
    I understand the need for DI using testing, injecting stubbs and such, but how does using a registry in the container class it make the code more simple?

    Your argument was that just doing DI makes it become quickly unmanageable. It looks like you had to set the same number of dependencies in the IoC class as you did with DI. The only difference was where you did that at.

    Two more questions, since all of your methods were static doesn’t that mean you should make the class itself static or abstract bc it looks like it never really is meant to be instantiated?

    By making it the properties / methods (the dependencies) abstract wouldn’t that help with identifying the dependencies because any client trying to consume your code would be forced to adhere to the abstract interface?

    Thanks for the clarification!!

    - Paul

    • Jon

      “Your argument was that just doing DI makes it become quickly
      unmanageable. It looks like you had to set the same number of
      dependencies in the IoC class as you did with DI. The only difference
      was where you did that at.”

      I think the point was that you only need to define those dependencies once, and in one location, rather than every time you make a new object.

      Let’s say you have a User class, which you will undoubtedly make use of in many different places of a large application. (Example, you’ll need to instantiate a new user when someone logs in, or when they post a comment, or when they update their profile etc).

      So rather than calling

      $user = new User();
      $user->dependency_1 = $something;
      $user->dependency_2 = $something;
      etc…

      every single time you instantiate a user, you can simply do

      $user = Make::object(‘User’);

      • http://mesuutt.com/ mesuutt

        $user = Make::object(‘User’);

        This is also a factory pattern example?

  • rob

    Thanks for the tutorial. It is awesome
    Although I was using DI in my code, but never fully understand it.

  • Kevin Searle

    The examples require 5.3.

    • http://twitter.com/eckert_ryan1 Eckert Ryan

      in retrospect – it is 2012 is it not?

      • Morticae

        it is not

  • http://blog.novalagung.com/ Noval Agung Prayogo

    cantik sekali :D

  • BenF

    I find the IoC quite difficult to understand, is there a working example anywhere that I’m missing? I’ve got a procedural background in PHP, and I struggle to understand classes, for example in here, how does it connect to my database? Sorry, I know this is a really dumb question. A really well fleshed out example would be a godsend

  • Riz

    // Also frequently called "Container"

    class IoC {

    /**

    * @var PDO The connection to the database

    */

    protected $db;

    /**

    * Create a new instance of Photo and set dependencies.

    */

    public static newPhoto()

    {

    $photo = new Photo;

    $photo->setDB(static::$db);

    // $photo->setConfig();

    // $photo->setResponse();

    return $photo;

    }

    }

    $photo = IoC::newPhoto();

    can anybody please explain why Factory pattern can not be used for this purpose? how is it different from Factory Design Pattern.?

    Thanks

  • Bolaji

    Thank you for this article and which I fully understand, but can someone please relate this article to the ZendDi class

  • http://www.facebook.com/oscar.blank.33 Oscar Blank

    I know it has been a long time since you posted this article, but I wanted to ask what you think about passing config parameters to the anonymous function when resolving. For instance, if you have multiple types of database connections, and you wanted to specify one, how would you do that? Would you need to make a seperate IoC registry for each connection type? In my own testing, I was able to pass a parameter to the anonymous function, but don’t know if this is considered the wrong thing to do.