【问题标题】:Symfony2: get Doctrine in a generic PHP classSymfony2:在通用 PHP 类中获取 Doctrine
【发布时间】:2012-08-10 17:21:50
【问题描述】:

在 Symfony2 项目中,当您使用 Controller 时,您可以通过在 this 上调用 getDoctrine() 来访问 Doctrine,即:

$this->getDoctrine();

这样,我就可以访问这样一个Doctrine Entity的仓库了。

假设在 Symfony2 项目中有一个通用的 PHP 类。如何检索 Doctrine ? 我想应该有这样的服务可以得到它,但我不知道是哪一个。

【问题讨论】:

    标签: php symfony doctrine


    【解决方案1】:

    您可以将此类注册为service 并将任何其他服务注入其中。假设你有 GenericClass.php 如下:

    class GenericClass
    {
        public function __construct()
        {
            // some cool stuff
        }
    }
    

    您可以将其注册为服务(通常在您的捆绑包的 Resources/config/service.yml|xml 中)并将 Doctrine 的实体管理器注入其中:

    services:
        my_mailer:
            class: Path/To/GenericClass
            arguments: [doctrine.orm.entity_manager]
    

    它会尝试将实体管理器注入(默认情况下)GenericClass 的构造函数。所以你只需要为它添加参数:

    public function __construct($entityManager)
    {
         // do something awesome with entity manager
    }
    

    如果您不确定应用程序的 DI 容器中有哪些服务可用,可以使用命令行工具查找:php app/console container:debug,它会列出所有可用服务及其别名和类。

    【讨论】:

    • 这将注入 EntityManager。如何通过它获取存储库?在控制器中,我可以按如下方式获取存储库:$this->getDoctrine() ->getRepository('AcmeUserBundle:Address');,我还可以按如下方式获取 EntityManager:$this->getDoctrine()->getEntityManager()。但是,已知 EntityManager,如何获取存储库?如果可以,那么答案就是你的!
    • 如果您查看基类 Controller 中的 getDoctrine,它只会调用 $this->container->get('doctrine')。所以你可以对你的服务做同样的事情(注入doctrine)。但是你可以通过调用$entityManager->getRepository('...')来达到同样的效果。
    • 对我不起作用,尽管服务已正确注册,但我收到“缺少参数”警告(我可以使用“控制台容器:调试”看到它)。
    【解决方案2】:

    查看 symfony2 文档后,我想出了如何通过您的服务 在自定义方法中打破默认行为。

    像这样重写你的配置:

    services:
    my_mailer:
        class: Path/To/GenericClass
        calls:
             - [anotherMethodName, [doctrine.orm.entity_manager]]
    

    因此,该服务现在可以通过您的其他方法使用。

    public function anotherMethodName($entityManager)
    {
        // your magic
    }
    

    Ondrej 的回答是绝对正确的,我只是想把这块拼图添加到这个帖子中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多