php - Symfony 2 EntityManager 注入(inject)服务

标签 php symfony dependency-injection

我已经创建了自己的服务,我需要注入(inject)学说 EntityManager,但是我没有看到在我的服务上调用了 __construct(),并且注入(inject)不起作用。

这里是代码和配置:

<?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" }

当我在 Controller 中调用服务时

    $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 对象的同一 Controller 中。

看起来我缺少配置或 UserService 和 Doctrine 配置之间的某些链接。

最佳答案

你的类的构造方法应该叫做__construct(),而不是__constructor():

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

关于php - Symfony 2 EntityManager 注入(inject)服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10427282/

相关文章:

php - Doctrine2 Symfony2 分页器因 orderBy 而失败

symfony - 哪个 Symfony2 bundle 更适合 Neo4j 集成?

dependency-injection - 向 Unity 注册

java - Guice MapBinder

c# - 在 Ninject 中部署

php - 设置不安全属性失败

php - !== 和 === 在 PHP 中是什么意思?

symfony - 类在 Sylius 中没有实现 "Symfony\Component\Form\FormTypeInterface"

php - SQL - Where 子句和 distinct

php - 操作 'like' 的排序规则 (utf8mb4_unicode_ci,IMPLICIT) 和 (utf8_general_ci,COERCIBLE) 的非法混合