Laravel 的 契约(Contracts) 是一组定义框架核心服务的接口(Interface)。它们规范了服务的公共方法,例如 Cache
契约规定了 get()
, put()
等方法。通过依赖这些接口而非具体实现,代码耦合度降低,灵活性和可测试性增强。
use Illuminate\Contracts\Cache\Factory as Cache;
class UserController extends Controller
{
protected $cache;
// 依赖注入 Cache 契约
public function __construct(Cache $cache)
{
$this->cache = $cache;
}
public function showProfile($id)
{
// 通过契约调用缓存
$user = $this->cache->get('user:'.$id, function () use ($id) {
return User::findOrFail($id);
});
return view('profile', ['user' => $user]);
}
}
use Illuminate\Contracts\Logging\Log;
class OrderService
{
protected $logger;
public function __construct(Log $logger)
{
$this->logger = $logger;
}
public function processOrder($order)
{
try {
// 处理订单逻辑...
} catch (Exception $e) {
$this->logger->error('订单处理失败', ['error' => $e->getMessage()]);
}
}
}
// app/Contracts/PaymentGateway.php
namespace App\Contracts;
interface PaymentGateway
{
public function charge($amount, $token);
public function refund($transactionId);
}
// app/Services/StripePaymentGateway.php
namespace App\Services;
use App\Contracts\PaymentGateway;
class StripePaymentGateway implements PaymentGateway
{
public function charge($amount, $token)
{
// Stripe 支付逻辑
return 'Charge successful with Stripe';
}
public function refund($transactionId)
{
// Stripe 退款逻辑
return 'Refund processed via Stripe';
}
}
// 在 AppServiceProvider 的 register 方法中
use App\Contracts\PaymentGateway;
use App\Services\StripePaymentGateway;
public function register()
{
$this->app->bind(PaymentGateway::class, StripePaymentGateway::class);
}
use App\Contracts\PaymentGateway;
class PaymentController extends Controller
{
protected $paymentGateway;
public function __construct(PaymentGateway $paymentGateway)
{
$this->paymentGateway = $paymentGateway;
}
public function processPayment(Request $request)
{
$result = $this->paymentGateway->charge(1000, $request->token);
return response()->json(['message' => $result]);
}
}
$this->app->bind(Contract::class, Implementation::class);
$this->app->singleton(Contract::class, Implementation::class);
$payment = app()->make(PaymentGateway::class);
// 在服务提供者中根据配置绑定
if (config('cache.driver') === 'redis') {
$this->app->bind(CacheContract::class, RedisCache::class);
} else {
$this->app->bind(CacheContract::class, FileCache::class);
}
interface EmailSender {
public function send($to, $content);
}
// 实现类:MailgunSender, SendGridSender...
// 根据配置动态绑定
Cache
, Queue
, Mail
等