Symfony2: 在通用的PHP类中获取Doctrine

4
在Symfony2项目中,当您使用控制器(Controller)时,可以通过在this上调用getDoctrine()来访问Doctrine,例如:
$this->getDoctrine();

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

假设在Symfony2项目中有一个通用的PHP类。如何检索Doctrine? 我想必定有这样的服务来获取它,但我不知道是哪一个。

2个回答

11

你可以将这个类注册为服务并注入任何其他服务。假设你有如下的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,我如何获取存储库?如果可以的话,那么答案就是你的! - JeanValjean
1
如果您查看基类Controller中的getDoctrine,它只是调用$this->container->get('doctrine')。所以你可以在你自己的服务中注入doctrine,并做同样的事情。但是,您也可以通过调用$entityManager->getRepository('...')来实现相同的效果。 - Ondrej Slinták
对我来说不起作用,尽管服务已经正确注册(我可以使用“console container:debug”看到它),但我收到了一个“缺少参数”的警告。 - Select0r

1

查看symfony2文档后,我找到了如何在自定义方法中传递您的服务以打破默认行为的方法。

请将您的配置重写为以下内容:

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

所以,该服务现在可以在您的其他方法中使用。
public function anotherMethodName($entityManager)
{
    // your magic
}

Ondrej的答案是完全正确的,我只想在这个帖子中补充一点这个难题的信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接