我想在我的捆绑中使用教义。在扩展Controller的类中使用它时:
$em = $this->getDoctrine()->getEntityManager();
如果我想在其他没有扩展Controller的类中使用doctrine。我知道这一点,我应该将学说定义为服务,我这样做:
php class:
namespace News\VillageNewsBundle\Services;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DoctrineService extends Controller
{
protected $em;
public function __construct(EntityManager $entityManager)
{
$this->em = $entityManager;
}
}
?>
service.yml
services:
doctrine:
class: News\VillageNewsBundle\Services\DoctrineService
arguments: - @doctrine.orm.default_entity_manager
config.yml
imports:
- { resource: "@NewsVillageNewsBundle/Resources/config/services.yml" }
什么时候我遇到这个错误的水平:
ErrorException: Catchable Fatal Error: Argument 1 passed to Symfony\Bridge\Doctrine\CacheWarmer\ProxyCacheWarmer::__construct() must be an instance of Doctrine\Common\Persistence\ManagerRegistry, instance of News\VillageNewsBundle\Services\DoctrineService given, called in /var/www/Symfony/app/cache/dev/appDevDebugProjectContainer.php on line 402 and defined in /var/www/Symfony/vendor/symfony/symfony/src/Symfony/Bridge/Doctrine/CacheWarmer/ProxyCacheWarmer.php line 34
答案 0 :(得分:1)
doctrine
已经是一项服务,这就是您收到此错误的原因。
为什么需要将教义包含在另一个服务中?学说已经是一项服务。您必须声明需要将doctrine用作服务的其他类,然后在该服务上注入实体管理器。
我们假设你有一个FooBar
类:
<?php
namespace News\VillageNewsBundle\Services;
use Doctrine\ORM\EntityManager;
class FooBar
{
protected $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
}
您只需将此类声明为服务并传递EntityManager
,如下所示:
services:
my_service:
class: News\VillageNewsBundle\Services\FooBar
arguments: ['@doctrine.orm.entity_manager']
答案 1 :(得分:0)
我认为您收到此错误的原因是您定义了已存在的doctrine
服务。只需更改名称,它应该可以正常工作:
<强> services.yml:强>
services:
some_other_name:
class: News\VillageNewsBundle\Services\DoctrineService
arguments: [@doctrine.orm.default_entity_manager]