【问题标题】:How can I add the Entity Manager to a custom class or service?如何将实体管理器添加到自定义类或服务?
【发布时间】:2011-11-05 17:52:33
【问题描述】:

在 Symfony2 中,如何将 Doctrine 的实体管理器添加到自定义类或服务中?

我试过$em = $this->get("doctrine.orm.entity_manager");$em = $this->getDoctrine()->getEntityManager();

两者都失败了,这导致我尝试使用我的自定义类/服务来扩展 Controller 类,结果它死在了一个巨大的火球中。

【问题讨论】:

    标签: doctrine-orm symfony


    【解决方案1】:

    您确实必须将您的控制器定义为服务才能访问EntityManager。上面提到的Controller::getDoctrine() 方法只是在检查了Doctrine 服务是否可用后调用$this->container->get('doctrine') 返回Doctrine Registry。

    只需让您的自定义类/控制器扩展 ContainerAware 并定义一个快捷方法,例如:

    public function getEntityManager() {
        return $this->container->get('doctrine')->getEntityManager();
    }
    

    请注意,在扩展/实现 ContainerAware 的类中它是 $this->container->get(..) 而不是 $this->get(..)

    【讨论】:

    • 像魅力一样工作!谢谢你的伙伴:)
    • 使用上述方法时,我得到“调用...中的非对象上的成员函数 get()”。
    • 你在扩展ContainerAware吗?
    • ContainerAware 在哪里?
    【解决方案2】:

    您需要将实体管理器服务注入您的自定义服务。您的服务定义应如下所示:

    my.service.name:
      class:     my\class
      arguments: [ @doctrine.orm.default_entity_manager ]
    

    确保您的服务的 __construct 方法将实体管理器作为参数。

    请参阅Service Container chapter 了解更多信息。

    顺便说一句,$this->getDoctrine() 是一种快捷方法,只能在扩展 Symfony\Bundle\FrameworkBundle\Controller\Controller 的类中使用

    【讨论】:

    • 在 Symfony 2.3 中,我使用的是“@doctrine.orm.entity_manager”。 “@doctrine.orm.entity_manager”和“@doctrine.orm.default_entity_manager”有区别吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 2010-10-05
    • 2020-11-19
    • 2020-06-02
    相关资源
    最近更新 更多