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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With