【发布时间】:2017-10-21 19:03:19
【问题描述】:
我已经创建了自己的服务,我需要注入学说 EntityManager,但我没有看到在我的服务上调用了 __construct(),并且注入不起作用。
这里是代码和配置:
<?php
namespace Test\CommonBundle\Services;
use Doctrine\ORM\EntityManager;
class UserService {
/**
*
* @var EntityManager
*/
protected $em;
public function __constructor(EntityManager $entityManager)
{
var_dump($entityManager);
exit(); // I've never saw it happen, looks like constructor never called
$this->em = $entityManager;
}
public function getUser($userId){
var_dump($this->em ); // outputs null
}
}
这是我的捆绑包中的services.yml
services:
test.common.userservice:
class: Test\CommonBundle\Services\UserService
arguments:
entityManager: "@doctrine.orm.entity_manager"
我已经在我的应用程序中导入了 config.yml 中的那个 .yml
imports:
# a few lines skipped, not relevant here, i think
- { resource: "@TestCommonBundle/Resources/config/services.yml" }
当我在控制器中调用服务时
$userservice = $this->get('test.common.userservice');
$userservice->getUser(123);
我得到一个对象(不是 null),但 UserService 中的 $this->em 为 null,正如我已经提到的,从未调用过 UserService 上的构造函数
还有一点,Controller 和 UserService 位于不同的包中(我确实需要它来保持项目的组织性),但仍然:其他一切都很好,我什至可以调用
$this->get('doctrine.orm.entity_manager')
在我用来获取 UserService 并获取有效(非空)EntityManager 对象的同一控制器中。
看起来我缺少配置或 UserService 和 Doctrine 配置之间的某些链接。
【问题讨论】:
-
你试过setter注入吗?有效吗?
-
如果'setter injection'是指在我的服务上为EntityManager添加setter方法并使用$this->get('doctrine.orm.entity_manager')作为参数调用控制器,那么是的,我试过了,它有效。但我真的很喜欢通过配置使用正确的注入
-
我的意思是:symfony.com/doc/current/book/… 无论如何
__constructor是错误。 -
嗯,比我还没有尝试过setter注入。 __construct 解决了这个问题,但无论如何,谢谢你的帮助!
标签: php symfony dependency-injection