问题描述
以下是代码和配置:
Here is the code and configs:
code> services.yml 在我的包
<?phpnamespace 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 }}
Here is services.yml
in my bundle
我在我的应用程序中将 config.yml 中导入了.yml
services: test.common.userservice: class: Test\CommonBundle\Services\UserService arguments: entityManager: "@doctrine.orm.entity_manager"
p>
I've imported that .yml in config.yml
in my app like that
imports:
# a few lines skipped, not relevant here, i think
- { resource: "@TestCommonBundle/Resources/config/services.yml" }
当我在控制器中调用服务器
And when I call service in controller
$userservice = $this->get('test.common.userservice');
$userservice->getUser(123);
我得到一个对象(非空),但 $ this-> UserService中的em
为null,正如我已经提到的,UserService中的构造函数从未被调用过
I get an object (not null), but $this->em
in UserService is null, and as I already mentioned, constructor on UserService has never been called
还有一件事,Controller和UserService不同的捆绑(我真的需要保持项目的组织),但仍然:其他工作正常,甚至可以调用
One more thing, Controller and UserService are in different bundles (I really need that to keep project organized), but still: everyting else works fine, I can even call
$this->get('doctrine.orm.entity_manager')
获取UserService并获取有效(不为null)EntityManager对象。
in same controller that I use to get UserService and get valid (not null) EntityManager object.
看起来我缺少配置或UserService和Doctrine配置之间的一些链接。
Look like that I'm missing piece of configuration or some link between UserService and Doctrine config.
推荐答案
您的类的构造方法应该称为 __ construct()
,而不是$ code> __ constructor():
Your class's constructor method should be called __construct()
, not __constructor()
:
public function __construct(EntityManager $entityManager)
{
$this->em = $entityManager;
}
这篇关于Symfony 2 EntityManager注入服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!