title: Symfony 2: dependency injection and traits
body: <p>I'm trying to find a way to use the Symfony 2 <a href="http://symfony.com/doc/current/components/dependency_injection/introduction.html">Dependency Injection component</a> with the new PHP 5.4 <a href="http://php.net/manual/en/language.oop5.traits.php">traits</a>.</p>
  
  <p>To make a long story short (not so short, actually), my project has decoupled View classes that all have their own, specific constructor. Each View can use zero or more view helpers, that are defined as traits:</p>
  
  
  
  <pre class="lang-php prettyprint-override"><code>trait TranslatorHelper
  {
      /**
       * @var Translator
       */
      protected $translator;
  
      /**
       * @param Translator $translator
       */
      protected function setTranslator(Translator $translator)
      {
          $this-&gt;translator = $translator;
      }
  
      /**
       * @param string $text
       * @return string
       */
      public function translate($text)
      {
          return $this-&gt;translator-&gt;translate($text);
      }
  }
  </code></pre>
  
  <p>-</p>
  
  <pre class="lang-php prettyprint-override"><code>class UserEditView extends AbstractView
  {
      use TranslatorHelper;
  
      public function __construct(User $user, UserEditForm $form)
      {
          // ...
      }
  }
  </code></pre>
  
  <p>I'd like to have a method in my controller, <code>renderView()</code>, that performs setter injection based on all the traits used by the View class, before rendering the View:</p>
  
  <pre class="lang-php prettyprint-override"><code>class Controller
  {
      public function renderView(View $view)
      {
          // Check what traits are used by $view, and inject their dependencies
          // {...}
  
  
          // Then render the View
          return $view-&gt;render();
      }
  }
  </code></pre>
  
  <p>Any idea on how to do this with the <code>DependencyInjection</code> component?</p>
  
  <p>The main problem is obviously that the Views won't be created by the DI container, but can be created anywhere in the application flow. It's only before they're rendered that the dependencies need to be injected.</p>
  
  <p>A last note: I'm not tied to the Symfony component. Any lead on another DI container would be appreciated as well.</p>