Symfony2从elendev小部件包访问实体管理器

时间:2014-04-07 14:14:38

标签: symfony

如何在twig中加载的类中提供doctrine连接? 我使用以下内容 https://github.com/Elendev/ElendevWidgetBundle

创建小部件,我需要的是访问在symfony中创建的数据库全局连接。

在zend中我会使用Zend_Registry作为例子。

我正在写这样的小部件:

<?php
namespace Test\Bundle\CommonBundle\Widget;
use Elendev\WidgetBundle\Annotation\Widget;

class Links {
    /**
    * @Widget(tag="links", priority=99)
    */
    public function links(){
        $twig = new \Twig_Environment(new \Twig_Loader_Filesystem(array(__DIR__."/views/")) );
        $links = new \Test\Bundle\CommonBundle\Entity\WidgetLinksData();
//how to i access entity manager from here?
        return $twig->render('links.html.twig', );
    }
}

1 个答案:

答案 0 :(得分:1)

您需要注入EntityManager 您的服务定义可能如下所示:

my_service:
    class: Test\Bundle\CommonBundle\Widget\Links
        # Add this 2 lines
        arguments:
            - @doctrine.orm.entity_manager
        tags:
            - {name: elendev.widget, method: memberDatas, tag: member_profile}

然后,EntityManager实例将被加载到您的类构造函数中,因此您只需抓住它:

use Doctrine\ORM\EntityManager;

class Links
{
    private $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }
}

你可以用它在你的课堂方法中做任何你需要的事情:

$this->em->find(...);

但是在一个twig扩展中注入EntityManager并不是一个“最佳实践”,你可以使用另一个服务来包装它。

有关使用symfony进行依赖注入的更多信息:http://symfony.com/doc/current/components/dependency_injection/introduction.html

相关问题