Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2: Dependency injection (DI) of Controllers

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.

like image 612
Václav Novotný Avatar asked Apr 11 '12 12:04

Václav Novotný


People also ask

What is DI in Symfony?

The DependencyInjection component implements a PSR-11 compatible service container that allows you to standardize and centralize the way objects are constructed in your application.

How to define controller as service in Symfony?

In Symfony, a controller does not need to be registered as a service. But if you're using the default services. yaml configuration, and your controllers extend the AbstractController class, they are automatically registered as services.

What is dependency injection stack overflow?

Dependency injection is a pattern to allow your application to inject objects on the fly to classes that need them, without forcing those classes to be responsible for those objects. It allows your code to be more loosely coupled, and Entity Framework Core plugs in to this same system of services.

What is PHP dependency injection?

Dependency injection is a procedure where one object supplies the dependencies of another object. Dependency Injection is a software design approach that allows avoiding hard-coding dependencies and makes it possible to change the dependencies both at runtime and compile time.


1 Answers

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.

like image 174
Cerad Avatar answered Oct 13 '22 21:10

Cerad