2014-02-17 26 views
0

我想在我的config.yml我怎麼能在我的自制服務使用getContainer()

services: 
    myfunc: 
     class: Acme\TopBundle\MyServices\MyFunc 
     arguments: [] 
在Acme的

\ TopBundle \ MyServices使用的EntityManager在自制的服務

\ MyFunc.php

namespace Acme\TopBundle\MyServices; 
use Doctrine\ORM\EntityManager; 

class MyFunc 
{ 
    public $em; 

    public function check(){ 
     $this->em = $this->getContainer()->get('doctrine')->getEntityManager(); // not work. 
. 
. 

它在調用方法check()時顯示錯誤。

Call to undefined method Acme\TopBundle\MyServices\MyFunc::getContainer() 

如何在myFunc類中使用getContainer()?

回答

3

由於您(幸運的是)沒有在您的myfunct服務中注入容器,因此您的服務中沒有可用的容器參考。

您可能不需要通過服務容器獲取實體管理器!請記住,在DIC允許您通過只他們需要

namespace Acme\TopBundle\MyServices; 

use Doctrine\ORM\EntityManager; 

class MyFunc 
{ 
    private $em; 

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

    public function check() 
    { 
     $this->em // give you access to the Entity Manager 

服務定義(在你的情況下,實體管理器)的相關服務來定製你的服務,

services: 
    myfunc: 
     class: Acme\TopBundle\MyServices\MyFunc 
     arguments: [@doctrine.orm.entity_manager] 

而且,

  • 考慮使用「通過setter注入」,以防您處理可選的依賴關係。
+0

謝謝你完美地解決了我的問題 – whitebear

0

你需要讓MYFUNC「集裝箱知道」:

namespace Acme\TopBundle\MyServices; 

use Symfony\Component\DependencyInjection\ContainerAware; 

class MyFunc extends ContainerAware // Has setContainer method 
{ 
    public $em; 

    public function check(){ 
     $this->em = $this->container->get('doctrine')->getEntityManager(); // not work. 

您的服務:

myfunc: 
    class: Acme\TopBundle\MyServices\MyFunc 
    calls: 
     - [setContainer, ['@service_container']] 
    arguments: [] 

我應該指出的是,注入容器通常不是必需的,是不可取的。您可以直接將實體管理器注入到MyFunc中。更好的辦法是注入你需要的任何實體庫。

+0

總是喜歡這些推倒的票。拜託人。如果你足夠投票,然後再增加一對並留下評論。 – Cerad