First off you should add a constructor to your class and pass in the @doctrine.dbal.%connection_name%_connection servicenamespace 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: defaultservices: 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-26 07:33