Symfony2 injecting Doctrine Dbal as service on constructor

痴心易碎 提交于 2019-12-12 04:47:19

问题


Trying to pass a Doctrine dbal connection to my construct in a controller.

I am following this link to do it but it is not working:

How do you access Doctrine DBAL in a Symfony2 service class?

Here is my service inside app/config/config.yml

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

Here is my controller with construct

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;    
    }
}

I get this error "message": "Catchable Fatal Error: Argument 1 passed to Test\TestBundle\Controller\FormController::__construct() must be an instance of Doctrine\DBAL\Connection, none given, called in /srv/test/tmp/dev/cache/classes.php on line 2449 and defined in /vagrant/test.com/src/Test/TestBundle/Controller/FormController.php

Here is app/config/routing.yml

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

Any help would be great. thx


回答1:


Ok. The basic problem is that _controller: TestTestBundle:Form:cget does not use the service container to create the FormController. Hence no injection. You need to configure the controller as a service.

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

Your routing will look like:

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

However, this will create a second problem since your controller ends up extending from the Symfony base controller which requires the container to be injected as well. So you need to adjust your service file to something like:

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

I think that should get you going.




回答2:


I don't know your service, maybe you need this: doctrine.dbal.default_connection.



来源:https://stackoverflow.com/questions/25795417/symfony2-injecting-doctrine-dbal-as-service-on-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!