13

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.

j0k
  • 22,600
  • 28
  • 79
  • 90
Václav Novotný
  • 804
  • 2
  • 7
  • 13

1 Answers1

12

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.

Cerad
  • 48,157
  • 8
  • 90
  • 92
  • 1
    Take a look at my [AbstractControllerBundle](https://github.com/elnur/ElnurAbstractControllerBundle). It's meant to provide you with a [parent service](http://symfony.com/doc/current/cookbook/service_container/parentservices.html) to simplify using controllers as services. – Elnur Abdurrakhimov Apr 11 '12 at 14:10
  • 9
    It doesn't look to me like FOSUser does this? Am I missing the point? Václav's question was about injecting them via the constructor method, whilst FOSUser does $this->container->get('service'); https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Controller/RegistrationController.php – Steve Jul 02 '12 at 15:14
  • *in fact it's recommended* - according to the [official documentation](https://symfony.com/doc/2.7/controller/service.html): "Defining controllers as services is not officially recommended by Symfony" – rybo111 Nov 27 '17 at 22:57
  • @rybo111 True though when I wrote this answer 5+ years ago the Symfony best practices document did not exist. And if you look at dependency injection vs service locator debates then dependency injection generally wins out. But what is interesting and relevant for today is that Symfony 4 defines controllers as services by default. The wheel turns. – Cerad Nov 28 '17 at 13:54