【问题标题】:Call to undefined method Doctrine\Bundle\DoctrineBundle\Registry::persist()调用未定义的方法 Doctrine\Bundle\DoctrineBundle\Registry::persist()
【发布时间】:2013-02-07 13:47:58
【问题描述】:

我最近将我的一个项目从 Symfony 2.0.x 升级到 2.1.x

一切正常,但是当我尝试在服务中持久化实体时,PHP 会抛出错误:

Call to undefined method Doctrine\Bundle\DoctrineBundle\Registry::persist()

在控制器中,一切正常。即使在服务中从数据库中获取对象也可以,但没有调用->persist($entity)

这是我的服务定义:

registration_form:
    class: KnowHow\ERegistration\BackendBundle\Service\RegistrationFormService
    arguments: [ @doctrine ]

还有我的班级:

 class RegistrationFormService
 {
     /** @var $em \Doctrine\ORM\EntityManager */
     private $em;

     /**
      * Ctor.
      *
      * @param $doctrine
      */
     public function __construct($doctrine)
     {
        $this->em = $doctrine;
     }
}

这没关系,但是当我尝试执行类似 thi $this->em->persist($entity) 之类的操作时,会抛出错误。

我不知道那里发生了什么。

【问题讨论】:

    标签: symfony doctrine-orm symfony-2.1


    【解决方案1】:

    你必须为你想要做的事情注入@doctrine.orm.entity_manager

    registration_form:
        class: KnowHow\ERegistration\BackendBundle\Service\RegistrationFormService
        arguments: [ @doctrine ]
                   ----^ (isn't good)
    

    修改为

    registration_form:
        class: KnowHow\ERegistration\BackendBundle\Service\RegistrationFormService
        arguments: [ @doctrine.orm.entity_manager ]
    

    或者,你必须使用做这样的事情(在你的构造函数中)

    public function __construct(Doctrine $doctrine)
    {
        $this->em = $doctrine->getEntityManager();
    }
    

    按照 Cyprian 的建议,我将添加 $doctrine 变量的类型以进行类型检查。不知道Doctrine 是否是正确的课程,但我想是的

    如果您不需要整个 doctrine 供应商,我建议只注入 entity_manager

    【讨论】:

    • 我只是补充一点,IMO 它也是一个好主意,你注入的强类型参数(例如,公共函数 __construct(Doctrine\ORM\EntityManager $doctrine))。它确实可以帮助您避免将来出现此类错误。
    • @Cyprian 你是对的,我会添加它(但它不是你建议的类:D)
    • @DonCallisto 我建议使用 phpdoc 以上属性,并从您的答案中选择服务名称(“docrine.orm.entity_manager”指的是 EntityManager)。当然对教义登记处的服务名称是“教义”。 :)
    猜你喜欢
    • 1970-01-01
    • 2018-02-08
    • 2014-12-13
    • 1970-01-01
    • 2018-09-21
    • 2016-02-19
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    相关资源
    最近更新 更多