Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2: dependency injection and traits

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

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:

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.

like image 478
BenMorel Avatar asked Jul 13 '12 18:07

BenMorel


1 Answers

Symfony 3.3 introduced the idea of autowired services.
All you have to do is create a setter function in your trait and add the @required annotation.

private $entityManager;

/**
 * @required
 * @param EntityManagerInterface $entityManager
 */
public function setEntityManager(EntityManagerInterface $entityManager)
{
    $this->entityManager = $entityManager;
}

Reference: https://symfony.com/doc/current/service_container/autowiring.html#autowiring-other-methods-e-g-setters

like image 145
Serg K Avatar answered Sep 25 '22 09:09

Serg K