Symfony 2: Dependency injection (DI) of Controller

2020-02-26 06:25发布

问题:

Is there any chance to make Controllers dependent on their services not via using of service container inside them but through pure constructor dependency injection?

I would like to write controllers in this way:

<?php

class ArticleController extends \Symfony\Bundle\FrameworkBundle\Controller\Controller
{
    private $articleFacade;
    private $articleRepository;

    public function __construct(ArticleFacade $articleFacade, ArticleRepository $articleRepository)
    {
        $this->articleFacade = $articleFacade;
        $this->articleRepository = $articleRepository;
    }

    public function indexAction()
    {
        ...
    }

}

Unfortunatelly as I can see Symfony ControllerResolver does new instances of Controllers not via ServiceContainer but via simple return new $controller call.

回答1:

Absolutely in fact it's recommended and if you look at most 3rd party bundles such as FOSUser you can see that that is exactly what they do.

The trick is to define your controllers as services and then use the service id instead of the class name.

http://symfony.com/doc/current/cookbook/controller/service.html

Keep in mind that you will have to inject all your needed services such as entity managers and you won't usually extend the symfony base class. Of course you could inject the complete container but that tends to be frowned on.