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

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


First off you should add a constructor to your class and pass in the @doctrine.dbal.%connection_name%_connection service

namespace Acme\TestBundle\Toolbox;use Doctrine\DBAL\Connection;class StringToolbox{    /**    *    * @var Connection    */    private $connection;    public function __construct(Connection $dbalConnection)  {        $this->connection = $dbalConnection;        }    public function lookupSomething($foo)    {    $sql = "SELECT bar FROM bar_list WHERE foo = :foo";    $stmt = $this->connection->prepare($sql);    $stmt->bindValue("foo", $foo);    $stmt->execute();    return $bar;    }}

Your service configuration should now look like this:

parameters: my_service_connection: defaultservices: toolbox:   class:        Acme\TestBundle\Toolbox\StringToolbox    arguments:   [@doctrine.dbal.%my_service_connection%_connection]

What you are saying with this configuration is "make me a service named toolbox that will receive the doctrine.dbal.default_connection service as the first constructor argument"

There are other injection methods besides Constructor injection and you should read the http://symfony.com/doc/current/book/service_container.html documentation to get a grasp of all possibilities (Setter injection, Factory injection, etc) and to better understand how Dependency Injection works


@doctrine.dbal.connection not working, As Igor says, @doctrine.dbal.connection is an abstract, use @doctrine.dbal.default_connection if you only have one db connection, or @doctrine.dbal.%connection_name%_connection where the %connection_name% placeholder the name of the connection that you want to inject.

Your service configuration should now look like this:

services: toolbox:   class:        Acme\TestBundle\Toolbox\StringToolbox    arguments:   [@doctrine.dbal.default_connection]