2011年12月5日月曜日

Custom Repository Class

Doctrineでは、Entityというものを使うけど、これは基本的にデータを保持するためだけのクラス。
で、実際に find などの様にデータベース上のデータをフェッチするには、Repository を使用する。

こんな感じ。(http://docs.symfony.gr.jp/symfony2/book/doctrine.htmlより引用)

  1. $product = $this->getDoctrine()  
  2.        -$gt;getRepository('AcmeStoreBundle:Product')  
  3.        -$gt;find($id);  


...で、このgetRepositoryを見てみると、

  1. /** 
  2.  * Gets the repository for an entity class. 
  3.  * 
  4.  * @param string $entityName The name of the entity. 
  5.  * @return EntityRepository The repository class. 
  6.  */  
  7. public function getRepository($entityName)  
  8. {  
  9.     $entityName = ltrim($entityName'\\');  
  10.     if (isset($this->repositories[$entityName])) {  
  11.         return $this->repositories[$entityName];  
  12.     }  
  13.   
  14.     $metadata = $this->getClassMetadata($entityName);  
  15.     $customRepositoryClassName = $metadata->customRepositoryClassName;  
  16.   
  17.     if ($customRepositoryClassName !== null) {  
  18.         $repository = new $customRepositoryClassName($this$metadata);  
  19.     } else {  
  20.         $repository = new EntityRepository($this$metadata);  
  21.     }  
  22.   
  23.     $this->repositories[$entityName] = $repository;  
  24.   
  25.     return $repository;  
  26. }  

の様になっている。

で、ここで注目するのは

  1. if ($customRepositoryClassName !== null) {  
  2.     $repository = new $customRepositoryClassName($this$metadata);  
  3. else {  
  4.     $repository = new EntityRepository($this$metadata);  
  5. }  

のとこ。つまりカスタムリポジトリクラスがあれば、それを使用するけど、そうじゃなきゃEntityRepositoryを使うよーってことですね。

ってことで、自分で Repositoryを作成するには、EntityRepositoryを継承して独自にカスタマイズすればOK。
データ取得とかはコントローラでなくてモデル側に書いたほうが良いので、そういうのは独自のリポジトリを用意してそこで処理をさせたほうが綺麗!

ってことらしいです。

0 コメント:

コメントを投稿

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More