Symfony2:在通用 PHP 类中获取 Doctrine [英] Symfony2: get Doctrine in a generic PHP class

查看:14
本文介绍了Symfony2:在通用 PHP 类中获取 Doctrine的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In a Symfony2 project, when you use a Controller, you can access Doctrine by calling getDoctrine() on this, i.e.:

$this->getDoctrine();

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

In this way, I can access the repository of such a Doctrine Entity.

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

Suppose to have a generic PHP class in a Symfony2 project. How can I retrieve Doctrine ? I suppose that there is such a service to get it, but I don't know which one.

推荐答案

你可以将这个类注册为一个服务 并向其中注入任何其他服务.假设你有 GenericClass.php 如下:

You can register this class as a service and inject whatever other services into it. Suppose you have GenericClass.php as follows:

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

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

You can register it as service (in your bundle's Resources/config/service.yml|xml usually) and inject Doctrine's entity manager into it:

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

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

And it'll try to inject entity manager to (by default) constructor of GenericClass. So you just have to add argument for it:

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

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

If you are not sure what services are available in your application's DI container, you can find out by using command line tool: php app/console container:debug and it'll list all available services along with their aliases and classes.

这篇关于Symfony2:在通用 PHP 类中获取 Doctrine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆