如何在 Symfony2 服务类中访问 Doctrine DBAL?
我正在学习 Symfony2(和 OOP),并且想要创建一个在我的应用程序中可用的服务。该服务接受一个值 foo,根据数据库表检查它,然后返回一个值 bar。
我有一个小类,
namespace Acme\TestBundle\Toolbox;
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: Acme\TestBundle\Toolbox
arguments: [@database_connection]
但它抛出一个错误,指出 get() 方法未定义。我陷入困境——如何在服务中使用 DBAL?谢谢!
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 Acme\TestBundle\Toolbox;
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: Acme\TestBundle\Toolbox
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您应该向您的类添加一个构造函数并传入
@doctrine.dbal.%connection_name%_connection 服务
您的服务配置现在应该如下所示:
您使用此配置所说的是“make我有一个名为 toolbox 的服务,它将接收Document.dbal.default_connection 服务作为第一个构造函数参数”
除了构造函数注入之外,还有其他注入方法,您应该阅读 http://symfony.com/doc/current/book/service_container.html 文档以掌握所有内容可能性(Setter 注入、工厂注入等)并更好地理解依赖注入的工作原理
First off you should add a constructor to your class and pass in the
@doctrine.dbal.%connection_name%_connection service
Your service configuration should now look like this:
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
不起作用,正如 Igor 所说,@doctrine.dbal.connection
是一个抽象,使用@doctrine.dbal.default_connection
> 如果您只有一个数据库连接,或@doctrine.dbal.%connection_name%_connection
其中%connection_name%
占位符是连接的名称你想要注射的。您的服务配置现在应如下所示:
@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: