php - Symfony2 : get Doctrine in a generic PHP class

标签 php symfony doctrine

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

$this->getDoctrine();

通过这种方式,我可以访问这样一个 Doctrine Entity 的存储库。

假设在 Symfony2 项目中有一个通用的 PHP 类。我怎样才能取回 Doctrine ? 我想有这样的服务可以获取它,但我不知道是哪一个。

最佳答案

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

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

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

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

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

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

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

关于php - Symfony2 : get Doctrine in a generic PHP class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11906426/

相关文章:

symfony - reCaptcha 和 GenemenuForm Bundle 的问题

symfony - Liip Imagine Bundle 图像的 Nginx 访问日志

php - Symfony2 : How to use INSERT DELAYED with doctrine or create a non-blocking database operation?

PHP 从数据库 WHERE 中计数

php - C PHP 扩展中的转换问题

php - Laravel Eloquent COUNT(*) 无结果 GroupBy()

symfony - 使用Twig访问对象方法

symfony - FOSUserBundle - PHPUnit - 模拟用户

symfony - Doctrine 2.5 : Unrecognized field (but only in Symfony's prod mode)

php - 重新加载时保存复选框状态