如何在 Symfony2 服务类中访问 Doctrine DBAL? [英] How do you access Doctrine DBAL in a Symfony2 service class?

查看:24
本文介绍了如何在 Symfony2 服务类中访问 Doctrine DBAL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Symfony2(和 OOP)并想创建一个在我的应用程序中可用的服务.该服务接受一个值 foo,根据数据库表检查它,并返回一个值 bar.

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.

我有一节课

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


}

我的设置是:

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

但是它抛出一个错误,说 get() 方法未定义.我被卡住了——如何在服务中使用 DBAL?谢谢!

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

推荐答案

首先你应该给你的类添加一个构造函数并传入@doctrine.dbal.%connection_name%_connection 服务

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]

您对这个配置的意思是让我成为一个名为工具箱的服务,它将接收 doctic.dbal.default_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"

除了构造函数注入之外还有其他注入方法,你应该阅读http://symfony.com/doc/current/book/service_container.html 文档以掌握所有可能性(Setter 注入、工厂注入等)并更好地了解依赖注入的工作原理

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

这篇关于如何在 Symfony2 服务类中访问 Doctrine DBAL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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