Symfony 2: dependency injection and traits
===

I'm trying to find a way to use the Symfony 2 [Dependency Injection component][1] with the new PHP 5.4 [traits][2].

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:

<!-- language-all: lang-php -->

    trait TranslatorHelper
    {
        /**
         * @var Translator
         */
        protected $translator;
    
        /**
         * @param Translator $translator
         */
        protected function setTranslator(Translator $translator)
        {
            $this->translator = $translator;
        }
    
        /**
         * @param string $text
         * @return string
         */
        public function translate($text)
        {
            return $this->translator->translate($text);
        }
    }

-

    class UserEditView extends AbstractView
    {
        use TranslatorHelper;
    
        public function __construct(User $user, UserEditForm $form)
        {
            // ...
        }
    }

I'd like to have a method in my controller, `renderView()`, that performs setter injection based on all the traits used by the View class, before rendering the View:

    class Controller
    {
        public function renderView(View $view)
        {
            // Check what traits are used by $view, and inject their dependencies
            // {...}
    
    
            // Then render the View
            return $view->render();
        }
    }

Any idea on how to do this with the `DependencyInjection` component?

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.

A last note: I'm not tied to the Symfony component. Any lead on another DI container would be appreciated as well.

  [1]: http://symfony.com/doc/current/components/dependency_injection/introduction.html
  [2]: http://php.net/manual/en/language.oop5.traits.php