Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

php - Symfony 2 EntityManager injection in service

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.

Here is the code and configs:

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

}

Here is services.yml in my bundle

services:
  test.common.userservice:
    class:  TestCommonBundleServicesUserService
    arguments: 
        entityManager: "@doctrine.orm.entity_manager"

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

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

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

in same controller that I use to get UserService and get valid (not null) EntityManager object.

Look like that I'm missing piece of configuration or some link between UserService and Doctrine config.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...