Symfony2:在一个通用的PHP类中获得Doctrine [英] Symfony2: get Doctrine in a generic PHP class

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

问题描述

在Symfony2项目中,当您使用控制器时,您可以通过调用 getDoctrine()访问 Doctrine 这个,即:

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

$this->getDoctrine();

以这种方式,我可以访问这样一个Doctrine实体的存储库。

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

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

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天全站免登陆