【问题标题】:Dynamic db in dependency injection依赖注入中的动态数据库
【发布时间】:2013-02-19 14:53:27
【问题描述】:

我在 symfony 2.0 中实现了多个数据库的概念。现在我需要在依赖注入的概念中动态获取 myservice.php 文件中的实体管理器。我怎么称呼这个实体经理?

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>

我的服务.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;
}

【问题讨论】:

    标签: database symfony dependency-injection entitymanager


    【解决方案1】:

    设置服务并注入原则:

    服务定义(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>')......
       }
    }
    

    【讨论】:

    • 我使用的是 services.xml 文件而不是 services.yml
    • @user1650898 我已经更新了我的答案 - 但我建议您阅读this 了解有关使用服务容器的更多详细信息
    • 我得到了错误:注意:未定义的属性:Traxcrm\CustomerCareBundle\Services\MyService::$container in /var/www/html/traxerpconstruction/src/Traxcrm/CustomerCareBundle/Services/MyService.php第 23 行
    • 您能否将您的来源添加到您的问题中 - 包括 MyService.php 文件和 services.xml
    • services.xml : symfony.com/schema/dic/services" xmlns:xsi="w3.org/2001/XMLSchema-instance" xsi:schemaLocation="symfony.com/schema/dic/services @987654325 @">
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    • 2017-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多