Skip to content

Laravel Pennant

Nguồn gốc: Bản dịch từ Laravel Pennant

Giới thiệu (Introduction)

Laravel Pennant là package feature flags nhẹ, không phức tạp — cho phép kiểm soát dần dần việc phát hành tính năng mới, A/B testing, và bảo vệ tính năng chưa hoàn thiện.

Cài đặt (Installation)

bash
composer require laravel/pennant

Publish migration:

bash
php artisan vendor:publish --provider="Laravel\Pennant\PennantServiceProvider"
bash
php artisan migrate

Configuration

File config/pennant.php cấu hình lưu trữ feature flag (database, array in-memory...).

Định nghĩa Features

Đăng ký feature trong AppServiceProvider:

php
use Laravel\Pennant\Feature;
use Illuminate\Support\Lottery;

Feature::define('new-onboarding-flow', function () {
    return Lottery::odds(1, 10);
});

Class Based Features

bash
php artisan pennant:feature NewOnboardingFlow

Kiểm tra Features

php
use Laravel\Pennant\Feature;

if (Feature::active('new-onboarding-flow')) {
    // ...
}

Conditional Execution

php
Feature::when('new-onboarding-flow',
    fn () => /* active */,
    fn () => /* inactive */,
);

HasFeatures Trait

Thêm trait HasFeatures vào User model:

php
if ($user->features()->active('new-onboarding-flow')) {
    // ...
}

Blade Directive

blade
@feature('new-onboarding-flow')
    <div>Nội dung mới</div>
@endfeature

Middleware

Bảo vệ route bằng feature flag middleware.

Scope

Đánh giá feature cho scope cụ thể (user, team...).

Specifying the Scope

php
Feature::for($user)->active('new-onboarding-flow');

Rich Feature Values

Feature có thể trả về giá trị phong phú (string, int...) thay vì chỉ boolean.

Eager Loading

Load trước feature flags cho nhiều scope để tránh N+1.

Cập nhật Values

php
Feature::activate('new-onboarding-flow');
Feature::deactivate('new-onboarding-flow');

Bulk Updates

Cập nhật feature cho tất cả scope cùng lúc.

Purging Features

Xóa stored values.

Testing

php
Feature::define('new-onboarding-flow', true);

Custom Drivers

Tự tạo driver lưu trữ feature flags.

Events

Pennant dispatch events: FeatureRetrieved, FeatureResolved, FeatureUpdated, FeatureDeleted, v.v.