2011-11-23 59 views
1

在Doctrine 2.1中似乎有一種看不見的情況,那就是不容易返回關聯的子集 集合。Doctine 2限制與DQL的關聯

http://www.doctrine-project.org/docs/orm/2.1/en/reference/limitations-and-known-issues.html#restricing-associations

該文檔建議寫一個庫find方法,這是有道理的,因爲這是我第一件事儘管這樣做的。

但是,如果沒有在實體內引用EntityManager,我看不到如何檢索關聯的存儲庫,這似乎無法將域與數據庫分離?

是否有針對此問題的推薦策略?

這是我對他們建議的解決方案的解釋。

class Category 
{ 
    protected $id; 
    protected $articles; // PesistentCollection 
    protected $em; // The EntityManager from somewhere? 

    public function getVisableArticles() 
    { 
     return $this->em->getRepository('Article') 
        ->getVisibleByCategory($this); 
    } 
} 

回答

1
  1. 在實體擁有的EntityManager不是在任何情況下 一件好事(注入你的倉庫,而不是)
  2. 類別不是文章的唯一根源,因爲它不能daterimne什麼文章你需要,所以你需要一個文章庫。

我會怎麼做:

class Category 
{ 
    protected $id; 
    protected $articles; // PesistentCollection 

    public function getVisableArticles(IArticleRepository $articleRepository) 
    { 
     return $articleRepository->getVisibleByCategory($this); 
    } 
} 

interface IArticleRepository 
{ 
    function getVisibleByCategory(Category $category); 
} 

你的學說的倉庫將實現IArticleRepository和類不會知道你的數據存儲/學說什麼。

+0

是的使用接口是答案,應該想到的!我猜在實體映射期間沒有任何種類的依賴注入,如果我有一個IArticleRepository的setter? – gawpertron

+0

沒有內置的依賴注入,doctrine只處理數據庫中的管理對象 – meze

+0

另一個想法是緩存結果嗎?如果我要創建一個新的可見文章,將它添加到PesistentCollection中,然後再次調用getVisibleArticles()將我的新文章出現在返回的數組中? – gawpertron