title: How to build a PHP Dependency Injection Container
body: <p>I've recently learned about the advantages of using Dependency Injection (DI) in my PHP application.  However, I'm still unsure how to create my container for the dependencies, or whether I should be using DI at all for the online forum that I'm building.</p>
  
  <p>The following code is my version of the DI container I have made based on the example I learned from <a href="http://net.tutsplus.com/tutorials/php/dependency-injection-huh/">here</a> .</p>
  
  <pre><code>class ioc {
  
     var $db;
     var $session;
     var $user_id;
  
     static function newUser(static::$db, static::$user_id) {
        $user = new User($db, $user_id);
        return $user;
     }
  
     static function newLogin(static::$db, static::$session) {
        $login = new Login($db, $session);
        return $login;
     }
  
  }
  
  $user = ioc::newUser();
  $login = ioc::newLogin();
  </code></pre>
  
  <p>I have a few questions: </p>
  
  <p>1) Where should I instantiate my injected dependencies, such as $database, $session, etc?  Would it be outside the container class, or inside the container's constructor.  </p>
  
  <p>2) What if I need to create a multiple instances of the User class inside other classes? I can't inject the previously instantiated $user object because that instance is already being used.  However, creating the multiple User instances inside of another class would violate the rules of DI.  For example:</p>
  
  <pre><code>class Users {
  
      function __construct($db, $user_id) {
          $this-&gt;db = $db;
          $this-&gt;user_id = $user_id;
      }
  
      function create_friends_list() {
          $st = $this-&gt;$db-&gt;prepare("SELECT user_id FROM friends WHERE user_id = $this-&gt;user_id");
          $st-&gt;execute();
          while($row = $st-&gt;fetch()) {
              $friend = ioc::newUser($row['user_id']);
              $friend-&gt;get_user_name();
              $friend-&gt;get_profile_picture();
          }
      }
  }   
  </code></pre>
  
  <p>3) I'm wondering if I should even adopt DI, knowing that I have to rewrite all of my previous code.  I've previously been relying on global variables that I instantiate in my initialize.php, which is included in all my files.  </p>
  
  <p>It seems to me that DI creates a lot of overhead and there are situations where it is unusable (as in my #2 example).  The following site is from a developer who cites many good reasons not to use DI. Does his arguments have any merit? Or am I just using DI wrong?
  <a href="http://www.tonymarston.net/php-mysql/dependency-injection-is-evil.html">check this link</a>.</p>