Symfony 2:控制器的依赖注入(DI) [英] Symfony 2: Dependency injection (DI) of Controllers

查看:124
本文介绍了Symfony 2:控制器的依赖注入(DI)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有机会使控制器依赖于他们的服务,而不是通过使用服务容器,而是通过纯构造函数依赖注入?

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()
    {
        ...
    }

}

不幸的是,我可以看到Symfony ControllerResolver没有通过ServiceContainer执行控件的新实例,但通过简单的返回新$控制器呼叫。

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

推荐答案

绝对是推荐的,如果你看看大多数第三方捆绑包,如FOSUser,你可以看到,这是什么他们这样做。

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

请记住,您将不得不注入所有您需要的服务,如实体管理员,您通常不会扩展symfony基类。当然,你可以注入完整的容器,但往往会皱起眉头。

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.

这篇关于Symfony 2:控制器的依赖注入(DI)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆