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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Take a look at my AbstractControllerBundle. It's meant to provide you with a parent service to simplify using controllers as services.
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'); github.com/FriendsOfSymfony/FOSUserBundle/blob/master/…
in fact it's recommended - according to the official documentation: "Defining controllers as services is not officially recommended by Symfony"
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.