2017-02-05 9 views
1

프로젝트에 doctrine ODM을 사용하고 각 클라이언트에 대해 별도의 데이터베이스를 가지고 있다고 생각했습니다. 내 API를 통해 런타임에 클라이언트를 관리 할 수 ​​있기를 원합니다. 내 질문은 지금 :Doctrine ODM 런타임에 데이터베이스 선택

내가 doctrine ODM을 설정하면 내 parameters.yml에 데이터베이스 설정을 설정해야하지만 런타임에 데이터베이스를 선택할 수 있기를 원합니다. 내 모든 조명기 컬렉션과 클라이언트 인덱스가있는 하나의 메인 데이터베이스를 가지고 선택할 데이터베이스를 알게 될 것이지만, 클라이언트 특정 물건은 그 클라이언트 데이터베이스에있게 될 것입니다. 각 Document 클래스는 일반적인 상황과 마찬가지로 컬렉션에 연결되지만 다른 데이터베이스에서는 여전히 컬렉션에 연결됩니다.

런타임시 Document 클래스의 데이터베이스를 선택하는 방법이 있습니까?

그래서 www.myproject.com/client1/item/list에 가도록합시다. dbclient1.Items 컬렉션의 모든 항목을 나열하고 www.myproject.com/client2/item/list로 이동하면 dbclient2.Items 컬렉션의 모든 항목을 나열합니다.

내가 여기에 도달하고 싶은 것을 분명히했으면 좋겠다. 나는 이것에 관해서 아무 것도 찾을 수 없었다. 그러나 내가 이것에 대해 질문을 한 최초의 사람이라면 이상 할 것이라고 생각한다. 똑같은 생각으로 나보다 먼저 사람이었을거야?

답변

0

런타임시 Document 클래스의 데이터베이스를 선택하는 방법이 있습니까?

예, 데이터베이스를 변경해야 할 때마다 $dm->getConfiguration()->setDefaultDb('some_db_name')을 호출 할 수 있지만 쓰기가 시작되면 예기치 않은 동작이 발생할 수 있습니다.

내 경험에 비추어 볼 때 (멀티 테넌트 앱에 대해 몇 년 동안 연습 한 경험이있다.) 각 상황에 따라 DocumentManager 개의 인스턴스를 만드는 것이 가장 탄탄합니다. 당신은 하나의 DocumentManager이 매개 변수를 사용하여 일반적으로 구성되어 있지만 직접 사용되지 않는함으로써 그것을 달성 할 수 - 대신 당신은 그것의 인스턴스를 관리하는 클래스), 철 (Fe이 필요합니다 : 몇 데이터베이스에서이 방법 문서에

use Doctrine\ODM\MongoDB\DocumentManager; 

class DocumentManagerFactory 
{ 
    /** 
    * DocumentManager created by Symfony. 
    * 
    * @var DocumentManager 
    */ 
    private $defaultDocumentManager; 

    /** 
    * All DocumentManagers created by Factory so far. 
    * 
    * @var DocumentManager[] 
    */ 
    private $instances = array(); 

    public function __construct(DocumentManager $dm) 
    { 
     $this->defaultDocumentManager = $dm; 
    } 

    public function createFor(Context $ctx) 
    { 
     $databaseName = $ctx->getDatabaseName(); 
     if (isset($this->instances[$databaseName])) { 
      return $this->instances[$databaseName]; 
     } 
     $configuration = clone $this->defaultDocumentManager->getConfiguration(); 
     $configuration->setDefaultDB($databaseName); 
     return $this->instances[$databaseName] = DocumentManager::create(
      $this->defaultDocumentManager->getConnection(), 
      $configuration, 
      $this->defaultDocumentManager->getEventManager() 
     ); 
    } 
} 

감사를 않습니다 하나의 DocumentManager에 의해 관리되는 경우 ODM 구성 및 프레임 워크 접근 방식으로 간섭하는 하나의 클래스가 있습니다 (이벤트 구독자 등은 각각 DocumentManager에 대해 동일합니다).