Symfony2在构造函数上注入Doctrine Dbal作为服务


Symfony2 injecting Doctrine Dbal as service on constructor

试图将Doctrine dbal连接传递到控制器中的构造。

我正在按照这个链接来做,但它不起作用:

如何在Symfony2服务类中访问Doctrine DBAL?

这是我在app/config/config.yml 中的服务

services:
 form1:
   class:       Test'TestBundle'Controller'FormController
   arguments:   [@doctrine.dbal.form1_connection]

这是我的控制器和构造

namespace Test'TestBundle'Controller;
use FOS'RestBundle'Controller'FOSRestController;
use FOS'RestBundle'Controller'Annotations as Rest;
use FOS'RestBundle'Routing'ClassResourceInterface;
use FOS'RestBundle'Util'Codes;
use Symfony'Component'HttpFoundation'Request;
use Symfony'Component'HttpKernel'Exception'HttpException;
use Doctrine'DBAL'Connection;

class FormController extends FOSRestController implements ClassResourceInterface
{
    private $connection;
    public function __construct(Connection $dbalConnection)  {
        $this->connection = $dbalConnection;    
    }
}

我得到了这个错误"消息":"可捕获的致命错误:传递给Test''TestBundle''Controller''FormController::__construct()的参数1必须是Doctrine''DBAL''Connection的实例,没有给出任何实例,在第2449行的/srv/Test/tmp/dev/cache/classes.php中调用,并在/varrant/Test.com/src/Test/TestBundle/Controller/FormController.php中定义

这是app/config/routing.yml

test_form:
    pattern:  /api/v4/forms.{_format}
    defaults: { _controller: TestTestBundle:Form:cget, _format: json }
    requirements:
        _method: GET

任何帮助都会很棒。thx

好的。基本问题是_controller:TestTestBundle:Form:cget没有使用服务容器来创建FormController。因此没有注射。您需要将控制器配置为服务。

http://symfony.com/doc/current/cookbook/controller/service.html

您的路线将看起来像:

test_form:
    pattern:  /api/v4/forms.{_format}
    defaults: { _controller: form1:cgetAction, _format: json }
    requirements:
        _method: GET

然而,这将产生第二个问题,因为您的控制器最终从Symfony基本控制器扩展而来,这也需要注入容器。因此,您需要将您的服务文件调整为以下内容:

services:
    form1:
        class:       Test'TestBundle'Controller'FormController
        arguments:   ['@doctrine.dbal.form1_connection']
        calls:
            - [setContainer, ['@service_container']]

我认为这应该会让你继续前进。

我不知道你的服务,也许你需要这个:doctrine.dbal.default_connection.