title: Composing a Controller class with Dependency Injection in PHP
body: <p>How to solve the problem of <strong>composing a Controller</strong> class in PHP, which should be:</p>
  
  <ul>
  <li>easily <strong>testable</strong> by employing Dependency Injection, </li>
  <li>provide <strong>shared objects</strong> for end programmer</li>
  <li>provide a way to <strong>load new user libraries</strong></li>
  </ul>
  
  <p><em>Look down, for controller instantiation with a Dependency injection framework</em></p>
  
  <hr>
  
  <p>The problem is, that derived Controllers may use whatever resources the programmer wants to (eg. the framework provides). How to create a unified access to shared resources (DB, User, Storage, Cache, Helpers), user defined Classes or another libraries? </p>
  
  <h2>Elegant solution?</h2>
  
  <p>There are several possible solutions to my problem, but neither one looks to be a elegant</p>
  
  <ul>
  <li>Try to pass all shared objects by <strong>constructor</strong>? (may create constructor even with 10 placeholders)</li>
  <li>Create <strong>getters, settters</strong>? (bloated code) <code>$controller-&gt;setApplication($app)</code></li>
  <li>Apply <strong>singletons on shared resources</strong>? <code>User::getInstance()</code> or <code>Database::getInstance()</code></li>
  <li>Use <strong>Dependency Injection container</strong> as a singleton for object sharing inside the controller?</li>
  <li>provide one <strong>global application singleton</strong> as a factory? (this one looks very used in php frameworks, hovewer it goes strongly against DI principles and Demeter's law)</li>
  </ul>
  
  <p>I understand, that creating strongly coupled classes is discouraged and banished for :), however I don't know how this paradigm applies to a starting point for other programmers (a Controller class), in which they should be able to access shared resources provided to the MVC architecture. I believe, that breaking up the controller class into smaller classes would somehow destroy the practical meaning of MVC.</p>
  
  <hr>
  
  <h2>Dependency Injection Framework</h2>
  
  <p>DI Framework looks like a viable choice. However the problem still persists. A class like Controller does not reside in the Application layer, but in the RequestHandler/Response layer. </p>
  
  <p><strong>How should this layer instantiate the controller?</strong></p>
  
  <ul>
  <li>pass the DI injector into this layer?</li>
  <li>DI Framework as a singleton?</li>
  <li>put isolated DI framework config only for this layer and create separate DI injector instance?</li>
  </ul>