Laravel 5 引入 Contracts(契約) 概念,本質上是一組定義框架核心服務的 PHP 接口。官方文檔指出:Contracts 旨在實現 鬆耦合 與 簡單性。本文從原理、使用流程、實戰範例三個維度深度剖析。
框架在 Illuminate\Contracts 命名空間下提供數十個介面,涵蓋認證、快取、配置、容器、加密、路由、隊列等核心服務。常見範例:
Illuminate\Contracts\Auth\GuardIlluminate\Contracts\Cache\RepositoryIlluminate\Contracts\Routing\RegistrarIlluminate\Contracts\Container\Containerregister() 方法中,將介面綁定至具體實現類。// app/Providers/AppServiceProvider.php
public function register() {
$this->app->bind(
'Illuminate\Contracts\Auth\Registrar',
'App\Services\Registrar'
);
}
// app/Http/Controllers/Auth/AuthController.php
use Illuminate\Contracts\Auth\Registrar;
public function __construct(Guard $auth, Registrar $registrar) {
$this->auth = $auth;
$this->registrar = $registrar;
$this->middleware('guest', ['except' => 'getLogout']);
}
容器會根據綁定關係,自動將 App\Services\Registrar 實例注入 $registrar 參數,實現零配置依賴注入。
cache = $cache;
}
public function find($id) {
if ($this->cache->has($id)) { /* ... */ }
}
}
若需改用 Redis、或 API 變更,必須修改所有依賴此類的代碼,專案越大風險越高。
cache = $cache;
}
}
現在 Repository 完全不關心底層是 Memcached、Redis 還是陣列快取,只需在服務提供者調整綁定即可切換實現,實現真正的「面向介面編程」。
Illuminate\Contracts\Cache\Repository vs Illuminate\Cache\CacheManager)。App::make('cache') 或 Cache::get() 等 Facade 靜態調用,改用依賴注入,提升可測試性。Contracts 是 Laravel 5 邁向企業級應用的關鍵基礎設施,善用它能讓代碼庫在長期演進中保持清晰、可維護、可替換。