我在将EntityManger注入Symfony2 twig-extension时遇到问题。我做了以下事情:
我注册了一个新的树枝扩展并创建了一个类。所有这一切都在发挥作用。 现在我想访问数据库并尝试注入Doctrine EnttrManager。我的第一步是将EM作为参数添加到构造函数中:
use XYZ\BlubBundle\Utils\SessionHelper;
class SessionHelperExtension extends \Twig_Extension
{
private $em;
private $conn;
protected $sessionHelper;
public function __construct(\Doctrine\ORM\EntityManager $em, \XYZ\BlubBundle\Utils\SessionHelper $sessionHelper) {
$this->em = $em;
$this->conn = $em->getConnection();
$this->sessionHelper = $sessionHelper;
}
[...]
}
?>
然后我将以下行添加到service.yaml:
twig.extension.sessionHelper:
class: XYZ\BlubBundle\Extensions\SessionHelperExtension
arguments: [@session_helper, @doctrine.orm.entity_manager]
tags:
- { name: twig.extension }
我自己的服务“sessionHelper”注入没有问题,但EntityManager始终为“null”。我在这里做错了什么?
编辑: 我得到以下异常:
Catchable Fatal Error: Argument 2 passed to
XYZ\BlubBundle\Extensions\SessionHelperExtension::__construct() must be an instance of
Doctrine\ORM\EntityManager, none given,
called in /.../Symfony/app/cache/dev/appDevDebugProjectContainer.php on line 2918 and
defined in /.../Symfony/src/XYZ/BlubBundle/Extensions/SessionHelperExtension.php line 12
答案 0 :(得分:2)
public function __construct(
\Doctrine\ORM\EntityManager $em,
\XYZ\BlubBundle\Utils\SessionHelper $sessionHelper
) {
错误 - 你需要像yml
中那样保持相同的顺序:
public function __construct(
\XYZ\BlubBundle\Utils\SessionHelper $sessionHelper,
\Doctrine\ORM\EntityManager $em
) {
试试这个:http://www.coderelic.com/2012/06/querying-the-database-from-a-twig-extension-in-symfony-2/