本文介绍了Symfony 2 EntityManager 注入服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've created my own service and I need to inject doctrine EntityManager, but I don't see that __construct() is called on my service, and injection doesn't work.

这是代码和配置:

<?php

namespace TestCommonBundleServices;
use DoctrineORMEntityManager;

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:  TestCommonBundleServicesUserService
    arguments:
        entityManager: "@doctrine.orm.entity_manager"

我已经在我的应用程序中的 config.yml 中导入了那个 .yml

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);

我得到了一个对象(非空),但 UserService 中的 $this->em 为空,而且正如我已经提到的,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 并获取有效(非空)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(),而不是__constructor():

Your class's constructor method should be called __construct(), not __constructor():

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

这篇关于Symfony 2 EntityManager 注入服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 06:39