Skip to content

Contracts

Giới thiệu (Introduction)

"Contracts" trong Laravel là tập hợp các interfaces định nghĩa core services của framework. Ví dụ:

  • Illuminate\Contracts\Queue\Queue — định nghĩa methods để queue jobs
  • Illuminate\Contracts\Mail\Mailer — định nghĩa methods để gửi email

Mỗi contract có implementation tương ứng do framework cung cấp. Tất cả contracts nằm trong GitHub repository riêng.

Contracts vs. Facades

Facades cung cấp cú pháp ngắn gọn để dùng services mà không cần type-hint trong constructor. Contracts cho phép bạn định nghĩa explicit dependencies cho classes.

Khi nào dùng cái nào?

Tiêu chíContractsFacades
CouplingLoose coupling — dễ swap implementationsConvenience — ít boilerplate
TestingDễ mock qua dependency injectionDễ mock qua Facade::shouldReceive()
Use casePackages, libraries tái sử dụngApplication code thông thường

Trong hầu hết ứng dụng, cả hai đều hoạt động tốt. Lựa chọn tùy thuộc vào preferences của team.

Khi nào dùng Contracts (When to Use Contracts)

Sử dụng Contracts khi bạn muốn:

  1. Loose coupling — dễ dàng thay đổi implementation
  2. Simplicity — khi classes có ít dependencies

Cách sử dụng Contracts (How to Use Contracts)

Type-hint interface trong constructor:

php
<?php

namespace App\Listeners;

use App\Events\OrderWasPlaced;
use App\Models\User;
use Illuminate\Contracts\Redis\Factory;

class CacheOrderInformation
{
    /**
     * Tạo instance mới.
     */
    public function __construct(
        protected Factory $redis,
    ) {}

    /**
     * Handle the event.
     */
    public function handle(OrderWasPlaced $event): void
    {
        // Dùng $this->redis...
    }
}

Service container tự động resolve implementation tương ứng.

Contract Reference

Bảng tham chiếu contracts phổ biến:

ContractFacade tương ứng
Illuminate\Contracts\Auth\FactoryAuth
Illuminate\Contracts\Auth\GuardAuth::guard()
Illuminate\Contracts\Bus\DispatcherBus
Illuminate\Contracts\Cache\FactoryCache
Illuminate\Contracts\Cache\RepositoryCache::driver()
Illuminate\Contracts\Config\RepositoryConfig
Illuminate\Contracts\Cookie\FactoryCookie
Illuminate\Contracts\Database\Events\MigrationEvent
Illuminate\Contracts\Encryption\EncrypterCrypt
Illuminate\Contracts\Events\DispatcherEvent
Illuminate\Contracts\Filesystem\CloudStorage::cloud()
Illuminate\Contracts\Filesystem\FactoryStorage
Illuminate\Contracts\Filesystem\FilesystemStorage::disk()
Illuminate\Contracts\Hashing\HasherHash
Illuminate\Contracts\Http\KernelApp
Illuminate\Contracts\Mail\MailerMail
Illuminate\Contracts\Notifications\FactoryNotification
Illuminate\Contracts\Queue\FactoryQueue
Illuminate\Contracts\Queue\QueueQueue::connection()
Illuminate\Contracts\Redis\FactoryRedis
Illuminate\Contracts\Routing\RegistrarRoute
Illuminate\Contracts\Routing\ResponseFactoryResponse
Illuminate\Contracts\Routing\UrlGeneratorURL
Illuminate\Contracts\Session\SessionSession::driver()
Illuminate\Contracts\Translation\TranslatorLang
Illuminate\Contracts\Validation\FactoryValidator
Illuminate\Contracts\View\FactoryView