Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

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

I'm learning Symfony2 (and OOP) and want to create a service that's available throughout my app. This service takes a value foo, checks it against a database table, and returns a value bar.

I have a little class

namespace AcmeTestBundleToolbox;

class StringToolbox
{
    public function lookupSomething($foo)
   {

        $conn = $this->get('database_connection');
        $sql = "SELECT bar FROM bar_list WHERE foo = :foo";
        $stmt = $conn->prepare($sql);
        $stmt->bindValue("foo", $foo);
        $stmt->execute();


        return $bar;
    }


}

My settings are:

services:
    toolbox:
       class:        AcmeTestBundleToolbox
        arguments:   [@database_connection]

But it throws an error saying that the get() method is undefined. I'm stuck-- how can I use DBAL in the service? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

namespace AcmeTestBundleToolbox;
use DoctrineDBALConnection;

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: default

services:
 toolbox:
   class:        AcmeTestBundleToolboxStringToolbox
    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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...