# 倉庫
Repository(代碼倉庫)是SF中的另一個重要概念。
顧名思義,代碼倉庫就是存放(通常是通用的)代碼的地方。在SF中,一般用來堆放進行數據庫操作的代碼。
SF為什么要增加這么一個額外的層?有兩個原因:
1. 雖然一個[實體](https://taylorr.gitbooks.io/building-a-web-site-with-symfony/content/03.05%20entity.html)提供了一些基本的數據庫操作,如`findOneBy`之類的,但是肯定不能滿足我們定制搜索的需要;
2. 如上的這個要求既不應該是Model的任務,更不應該是Controller的任務(不符合DRY和代碼重用原則)。
所以,我們有必要加入一個新的層,形成這樣的一個關系圖:

1. Controller只提出我要什么數據;
2. Repository只負責選擇數據;
3. Model存放真正的數據。
現在要馬上透徹理解這里的關系和區別還是比較困難的。我們會在后續文章中更深入地討論這些。
我們來看一個典型的倉庫的代碼:
~~~
<?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
use Symfony\VarDumper;
/**
* StatusRepo
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class StatusRepo extends EntityRepository
{
public function getStatusIn($start, $end, $count = 4)
{
$inter_s = new \DateInterval($start);
$inter_e = new \DateInterval($end);
$cts = new \DateTime();
$cts->sub($inter_s);
$cte = new \DateTime();
$cte->sub($inter_e);
$em = $this->getEntityManager();
$repo = $em->getRepository('AppBundle:Status');
$q = $repo->createQueryBuilder('s')
->leftJoin('AppBundle:User', 'u', 'with', 'u=s.author')
->where('s.created>=:e')
->setParameter('e', $cte)
->andWhere('s.created<=:s')
->setParameter('s', $cts)
->setMaxResults($count)
->orderBy('s.created', 'desc')
->addOrderBy('s.id', 'desc')
->getQuery()
;
$status = $q->getResult();
return $status;
}
}
~~~
`getStatusIn`方法會提供在開始和結束期間的數據,缺省是提供4個。顯然,這個數據的提供(搜索)不是簡單地由`findBy`之類的實體方法可以完成的。
上面我們看到的構建SQL的方法是兩種可用方法中的一種,即通過鏈接各個函數調用,在查詢構造中中加入`join`、`where`、`order by`等限定而得到我們需要的一個`select`語句。
對其的調用在Controller中一般這樣進行:
~~~
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository('AppBundle:Status');
$day = $repo->getStatusIn('P0D', 'P1D', 5);
$week = $repo->getStatusIn('P1D', 'P7D');
$month = $repo->getStatusIn('P7D', 'P1M', 5);
... ...
~~~
這幾乎是一個標準的調用模式。
重要更新:如今的一種開發方式將我們從這樣的重度耦合中解放了出來。因此不再需要Repository,而直接改用遠程RESTful API的調用。詳細的討論可以參見[03.01 MVC](https://taylorr.gitbooks.io/building-a-web-site-with-symfony/content/03.01%20mvc.html)。
- 引言
- 1 LAMP
- 1.1 安裝虛擬機
- 1.2 安裝Vagrant
- 1.3 安裝Ubuntu
- 1.4 安裝Apache 2
- 1.5 安裝PHP
- 1.6 安裝MySQL服務器
- 1.7 最后的微調
- 1.8 設置一個虛擬主機
- 1.9 一個趁手的IDE
- 2 Symfony 3和重要構件
- 2.1 Symfony 3
- 2.2 Doctrine
- 2.3 Twig
- 2.4 Composer
- 3 Symfony重要概念
- 3.1 MVC
- 3.2 Bundle/包
- 3.3 Route/路由
- 3.4 Controller/控制器
- 3.5 Entity/實體
- 3.6 Repository/倉庫
- 3.7 Template/模板
- 3.8 Test/測試
- 4 藏書管理程序的結構
- 5 創建應用
- 5.1 建立版本管理
- 5.2 建立數據庫
- 5.3 應用結構
- 5.4 建立數據庫實體
- 5.5 樣本數據
- 5.6 路由
- 5.7 模板
- 5.8 開始編寫首頁
- 5.9 書籍詳情頁面
- 5.10 書籍列表頁面
- 5.11 書籍搜索
- 6 用戶和后臺
- 7 結語