# Contracts
- [簡介](#introduction)
- [Contracts Vs. Facades](#contracts-vs-facades)
- [何時使用 Contracts](#when-to-use-contracts)
- [低耦合](#loose-coupling)
- [簡單性](#simplicity)
- [如何使用 Contracts](#how-to-use-contracts)
- [Contract 參考](#contract-reference)
<a name="introduction"></a>
## 簡介
Laravel 的 Contracts 是一組定義了框架核心服務的接口。例如,`Illuminate\Contracts\Queue\Queue` contract 定義了隊列任務所需要的方法,而 `Illuminate\Contracts\Mail\Mailer` contract 定義了寄送 e-mail 需要的方法。
框架對于每個 contract 都有提供對應的實現,例如,Laravel 提供各種驅動程序的隊列實現,以及由 [SwiftMailer](http://swiftmailer.org/) 提供的 mailer 實現。
Laravel 所有的 contracts 都放在各自的 [GitHub 代碼庫](https://github.com/illuminate/contracts)。除了提供給所有可用的 contracts 一個快速的參考,也可以單獨作為一個低耦合的擴展包來讓其他擴展包開發者使用。
<a name="contracts-vs-facades"></a>
### Contracts Vs. Facades
Laravel 的 [facades](/docs/{{version}}/facades) 提供一個簡單的方法來使用服務,而不需要使用類型約束和在服務容器之外解析 contracts。大多數情況下,每個 facade 都有一個相應的 contract。
不像 facades 那樣,contracts 需要你為你的類顯示的定義依賴關系。有些開發者喜歡這種顯示的依賴定義,所以他們喜歡使用 contracts,而其他開發者更喜歡方便的 facades。
> {tip} 大多數應用不管你是使用 facades 還是 contracts 都可以很好的工作,但是如果你打算構建擴展包的話,強烈建議使用 contracts,因為它們在擴展包的環境下更容易被測試。
<a name="when-to-use-contracts"></a>
## 何時使用 Contracts
正如我們所說,到底是選擇 facade 還是 contracts 取決于你或你的團隊的喜好。不管是 facade 還是 contracts,都可以創建出健壯的,易測試的應用。隨著你長期關注于類的功能層面,你會發現其實 facades 和 contracts 之間并沒有太大的區別。
你可能有很多關于 contracts 的問題。像是為什么要使用接口?使用接口會不會變的更復雜?讓我們來提煉一下這樣做的原因:低耦合和簡單性。
<a name="loose-coupling"></a>
### 低耦合
首先,讓我們來查看這一段和緩存功能有高耦合的代碼,如下:
<?php
namespace App\Orders;
class Repository
{
/**
* 緩存實例。
*/
protected $cache;
/**
* 創建一個新的倉庫實例。
*
* @param \SomePackage\Cache\Memcached $cache
* @return void
*/
public function __construct(\SomePackage\Cache\Memcached $cache)
{
$this->cache = $cache;
}
/**
* 借由 ID 獲取訂單信息。
*
* @param int $id
* @return Order
*/
public function find($id)
{
if ($this->cache->has($id)) {
//
}
}
}
在此類中,程序和緩存實現之間是高耦合。因為它是依賴于擴展包的特定緩存類。一旦這個擴展包的 API 更改了,我們的代碼也要跟著改變。
同樣的,如果想要將底層的緩存實現(比如 Memcached )切換成另一種(像 Redis ),又一次的我們必須修改這個 `Repository` 類。我們的 `Repository` 類不應該知道這么多關于誰提供了數據,或是如何提供等細節。
**比起上面的做法,我們可以使用一個簡單、和擴展包無關的接口來改進代碼:**
<?php
namespace App\Orders;
use Illuminate\Contracts\Cache\Repository as Cache;
class Repository
{
/**
* 緩存實例。
*/
protected $cache;
/**
* 創建一個新的倉庫實例。
*
* @param Cache $cache
* @return void
*/
public function __construct(Cache $cache)
{
$this->cache = $cache;
}
}
現在上面的代碼沒有跟任何擴展包耦合,甚至是 Laravel。既然 contracts 擴展包沒有包含實現和任何依賴,你就可以很簡單的對任何 contract 進行實現,你可以很簡單的寫一個替換的實現,甚至是替換 contracts,讓你可以替換緩存實現而不用修改任何用到緩存的代碼。
<a name="simplicity"></a>
### 簡單性
當所有的 Laravel 服務都使用簡潔的接口定義,就能夠很容易決定一個服務需要提供的功能。 **可以將 contracts 視為說明框架特色的簡潔文檔。**
除此之外,當依賴的接口足夠簡潔時,代碼的可讀性和可維護性大大提高。比起搜索一個大型復雜的類里有哪些可用的方法,你有一個簡單,干凈的接口可以參考。
<a name="how-to-use-contracts"></a>
## 如何使用 Contracts
那么,如何獲取一個 contract 的實現呢?其實真的非常簡單。
Laravel 里很多類型的類都是通過[服務容器](/docs/{{version}}/container)解析出來的。包括控制器,事件監聽器,中間件,任務隊列,甚至是路由的閉包。所以說,想要獲得一個 contract 的實現,你只需要在類的構造函數里添加相應的類型約束就好了。
舉個例子,看一下這個事件監聽器:
<?php
namespace App\Listeners;
use App\User;
use App\Events\OrderWasPlaced;
use Illuminate\Contracts\Redis\Database;
class CacheOrderInformation
{
/**
* Redis 數據庫實現。
*/
protected $redis;
/**
* 創建事件處理器實例。
*
* @param Database $redis
* @return void
*/
public function __construct(Database $redis)
{
$this->redis = $redis;
}
/**
* 處理事件。
*
* @param OrderWasPlaced $event
* @return void
*/
public function handle(OrderWasPlaced $event)
{
//
}
}
當事件監聽器被解析時,服務容器會從構造函數里讀取到類型約束,并且注入合適的類。想了解如何注冊綁定到容器,請參考[這篇文檔](/docs/{{version}}/container)。
<a name="contract-reference"></a>
## Contract 參考
下面的表格提供了 Laravel contracts 及其對應的 facades 的參考:
Contract | References Facade
------------- | -------------
[Illuminate\Contracts\Auth\Factory](https://github.com/illuminate/contracts/blob/master/Auth/Factory.php) | Auth
[Illuminate\Contracts\Auth\PasswordBroker](https://github.com/illuminate/contracts/blob/master/Auth/PasswordBroker.php) | Password
[Illuminate\Contracts\Bus\Dispatcher](https://github.com/illuminate/contracts/blob/master/Bus/Dispatcher.php) | Bus
[Illuminate\Contracts\Broadcasting\Broadcaster](https://github.com/illuminate/contracts/blob/master/Broadcasting/Broadcaster.php) |
[Illuminate\Contracts\Cache\Repository](https://github.com/illuminate/contracts/blob/master/Cache/Repository.php) | Cache
[Illuminate\Contracts\Cache\Factory](https://github.com/illuminate/contracts/blob/master/Cache/Factory.php) | Cache::driver()
[Illuminate\Contracts\Config\Repository](https://github.com/illuminate/contracts/blob/master/Config/Repository.php) | Config
[Illuminate\Contracts\Container\Container](https://github.com/illuminate/contracts/blob/master/Container/Container.php) | App
[Illuminate\Contracts\Cookie\Factory](https://github.com/illuminate/contracts/blob/master/Cookie/Factory.php) | Cookie
[Illuminate\Contracts\Cookie\QueueingFactory](https://github.com/illuminate/contracts/blob/master/Cookie/QueueingFactory.php) | Cookie::queue()
[Illuminate\Contracts\Encryption\Encrypter](https://github.com/illuminate/contracts/blob/master/Encryption/Encrypter.php) | Crypt
[Illuminate\Contracts\Events\Dispatcher](https://github.com/illuminate/contracts/blob/master/Events/Dispatcher.php) | Event
[Illuminate\Contracts\Filesystem\Cloud](https://github.com/illuminate/contracts/blob/master/Filesystem/Cloud.php) |
[Illuminate\Contracts\Filesystem\Factory](https://github.com/illuminate/contracts/blob/master/Filesystem/Factory.php) | File
[Illuminate\Contracts\Filesystem\Filesystem](https://github.com/illuminate/contracts/blob/master/Filesystem/Filesystem.php) | File
[Illuminate\Contracts\Foundation\Application](https://github.com/illuminate/contracts/blob/master/Foundation/Application.php) | App
[Illuminate\Contracts\Hashing\Hasher](https://github.com/illuminate/contracts/blob/master/Hashing/Hasher.php) | Hash
[Illuminate\Contracts\Logging\Log](https://github.com/illuminate/contracts/blob/master/Logging/Log.php) | Log
[Illuminate\Contracts\Mail\MailQueue](https://github.com/illuminate/contracts/blob/master/Mail/MailQueue.php) | Mail::queue()
[Illuminate\Contracts\Mail\Mailer](https://github.com/illuminate/contracts/blob/master/Mail/Mailer.php) | Mail
[Illuminate\Contracts\Queue\Factory](https://github.com/illuminate/contracts/blob/master/Queue/Factory.php) | Queue::driver()
[Illuminate\Contracts\Queue\Queue](https://github.com/illuminate/contracts/blob/master/Queue/Queue.php) | Queue
[Illuminate\Contracts\Redis\Database](https://github.com/illuminate/contracts/blob/master/Redis/Database.php) | Redis
[Illuminate\Contracts\Routing\Registrar](https://github.com/illuminate/contracts/blob/master/Routing/Registrar.php) | Route
[Illuminate\Contracts\Routing\ResponseFactory](https://github.com/illuminate/contracts/blob/master/Routing/ResponseFactory.php) | Response
[Illuminate\Contracts\Routing\UrlGenerator](https://github.com/illuminate/contracts/blob/master/Routing/UrlGenerator.php) | URL
[Illuminate\Contracts\Support\Arrayable](https://github.com/illuminate/contracts/blob/master/Support/Arrayable.php) |
[Illuminate\Contracts\Support\Jsonable](https://github.com/illuminate/contracts/blob/master/Support/Jsonable.php) |
[Illuminate\Contracts\Support\Renderable](https://github.com/illuminate/contracts/blob/master/Support/Renderable.php) |
[Illuminate\Contracts\Validation\Factory](https://github.com/illuminate/contracts/blob/master/Validation/Factory.php) | Validator::make()
[Illuminate\Contracts\Validation\Validator](https://github.com/illuminate/contracts/blob/master/Validation/Validator.php) |
[Illuminate\Contracts\View\Factory](https://github.com/illuminate/contracts/blob/master/View/Factory.php) | View::make()
[Illuminate\Contracts\View\View](https://github.com/illuminate/contracts/blob/master/View/View.php) |
## 譯者署名
| 用戶名 | 頭像 | 職能 | 簽名 |
|---|---|---|---|
| [@dinghua](https://phphub.org/users/294) | <img class="avatar-66 rm-style" src="https://dn-phphub.qbox.me/uploads/avatars/294_1473147991.png?imageView2/1/w/100/h/100"> | 翻譯 | 專注于 PHP 和 Laravel |
- 說明
- 翻譯說明
- 發行說明
- 升級說明
- 貢獻導引
- 入門指南
- 安裝
- 配置信息
- 文件夾結構
- 錯誤與日志
- 開發環境
- HomeStead
- Valet
- 核心概念
- 服務容器
- 服務提供者
- 門面(facades)
- contracts
- HTTP層
- 路由
- 中間件
- CSRF保護
- 控制器
- 請求
- 響應
- Session
- 表單驗證
- 視圖與模板
- 視圖
- Blade模板
- 本地化
- Javascript與CSS
- 入門指南
- laravel-elixir
- 安全
- 用戶認證
- 用戶授權
- 重置密碼
- API授權
- 加密解密
- 哈希
- 綜合話題
- 廣播系統
- 緩存系統
- 事件系統
- 文件存儲
- 郵件發送
- 消息通知
- 隊列
- 數據庫
- 快速入門
- 查詢構造器
- 分頁
- 數據庫遷移
- 數據填充
- redis
- Eloquent ORM
- 快速入門
- 模型關聯
- Eloquent集合
- 修改器
- 序列化
- Artisan控制臺
- Artisan 命令行
- 任務調度
- 測試
- 快速入門
- 應用程序測試
- 數據庫測試
- 模擬器
- 官方擴展包
- Cashier交易包
- Envoy 部署工具
- Passport OAuth 認證
- Scout 全文搜索
- Socialite 社交化登錄
- 附錄
- 集合
- 輔助函數
- 擴展包開發
- 交流說明