Symfony2服务容器中的使用原则 [英] Symfony2 Use Doctrine in Service Container
问题描述
如何在服务容器中使用Doctrine?
代码只会导致错误消息致命错误:调用未定义的方法... :: get( )。
<?php
命名空间... \Service;
请使用Doctrine\ORM\EntityManager;
使用... \Entity\Header;
class dsdsf
{
protected $ em;
public function __construct(EntityManager $ em)
{
$ this-> em = $ em;
}
public function create()
{
$ id = 10;
$ em = $ this-> get('doctrine') - > getEntityManager();
$ em-> getRepository('...') - > find($ id);
}
}
services.yml
服务:
网站:
类:... \Service\Site
根据您的代码,您已经有一个 EntityManager
$ em = $ this-> get('doctrine') - > getEntityManager() - 只需使用 $如果您没有注入
EntityManager
。
,请阅读此。
更新:
您需要使容器将 EntityManager
注入您的服务。以下是在 config.yml
中执行此操作的示例:
服务:
/ pre>
your.service:
class:YourVendor\YourBundle\Service\YourService
arguments:[@ doctrine.orm.entity_manager]
我更喜欢在他们自己的
services.yml
文件中定义捆绑服务,但这是一个更高级的,所以使用config.yml
足够开始。How do I use Doctrine in a service container?
The Code just causes an error message "Fatal error: Call to undefined method ...::get()".
<?php namespace ...\Service; use Doctrine\ORM\EntityManager; use ...\Entity\Header; class dsdsf { protected $em; public function __construct(EntityManager $em) { $this->em = $em; } public function create() { $id = 10; $em = $this->get('doctrine')->getEntityManager(); $em->getRepository('...')->find($id); } }
services.yml
service: site: class: ...\Service\Site
解决方案According to your code, you already have an
EntityManager
injected. You don't need to call$em = $this->get('doctrine')->getEntityManager()
— just use$this->em
.If you don't inject an
EntityManager
already, read this.UPDATE:
You need to make the container inject an
EntityManager
into your service. Here's an example of doing it inconfig.yml
:services: your.service: class: YourVendor\YourBundle\Service\YourService arguments: [ @doctrine.orm.entity_manager ]
I prefer to define bundles' services in their own
services.yml
files, but that's a bit more advanced, so usingconfig.yml
is good enough to get started.这篇关于Symfony2服务容器中的使用原则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!