2013-03-05 186 views
1

我在symfony 2.0中實現了多個db概念。現在我需要在依賴注入的概念中在myservice.php文件中動態獲取實體管理器。我怎樣才能打電話給這個實體經理?依賴注入動態db

的services.xml:

 <container xmlns="http://symfony.com/schema/dic/services" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:schemaLocation="http://symfony.com/schema/dic/services         http://symfony.com  /schema/dic/services/services-1.0.xsd"> 

<services> 
    <service id="my_service" class="Traxcrm\SalesBundle\Services\MyService"> 
     <argument type="service" id="doctrine" /> 
    </service> 
</services> 

</container> 

mysevice.php

class MyService { 

private $doctrine; 

public function __construct(Doctrine\Bundle\DoctrineBundle\Registry $doctrine) 
{ 

    $this->doctrine = $doctrine;    

} 
class MyService { 

private $doctrine; 

public function __construct(Doctrine\Bundle\DoctrineBundle\Registry $doctrine) { 

    $this->doctrine = $doctrine; 
} 

public function getUserDetails($id) { 

    $query = $this->doctrine->getEntityManager('Test')->createQuery("SELECT  p   FROM  TraxcrmSigninBundle:Tblallusers p where p.id=$id"); 
    $userDetails = $query->getArrayResult(); 

    return $userDetails; 
} 

回答

0

設置服務和注入教義:

服務定義(services.yml或config.yml):

services: 
    service_name: 
     class: <namespace>myservice.php 
     arguments: ['@doctrine'] 

或XML:

<services> 
    <service id="service_name" class="<namespace>myservice.php"> 
     <argument type="service" id="doctrine"/> 
    </service> 
</services> 

然後設置你的類來接受教義傳入的對象

public class myservice { 

    private $doctrine; 

    public function __construct(Doctrine\Bundle\DoctrineBundle\Registry $doctrine) { 
     $this->doctrine = $doctrine; 
    } 

    public function aFunction() { 
     $em = $this->doctrine->getEntityManager('<name>')...... 
    } 
} 
+0

我使用services.xml文件不services.yml – Niju 2013-03-05 10:36:48

+0

@ user1650898我已經更新了我的答案 - 但我建議你可以閱讀[this](http://symfony.com/doc/current/book/service_container.html)瞭解更多有關使用服務容器的詳細信息 – ManseUK 2013-03-05 10:42:29

+0

抱歉.....謝謝,現在只能看到解決方案。我正在嘗試該方法 – Niju 2013-03-05 10:47:54