Skip to content

Laravel Pennant

介绍

Laravel Pennant 是一个简单且轻量级的特性标志包 - 没有多余的内容。特性标志使您能够逐步推出新的应用程序功能,进行 A/B 测试新的界面设计,补充基于主干的开发策略等等。

安装

首先,使用 Composer 包管理器将 Pennant 安装到您的项目中:

shell
composer require laravel/pennant

接下来,您应该使用 vendor:publish Artisan 命令发布 Pennant 的配置和迁移文件:

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

最后,您应该运行应用程序的数据库迁移。这将创建一个 features 表,Pennant 使用它来为其 database 驱动提供支持:

shell
php artisan migrate

配置

发布 Pennant 的资源后,其配置文件将位于 config/pennant.php。此配置文件允许您指定 Pennant 将用于存储已解析特性标志值的默认存储机制。

Pennant 包括支持将已解析的特性标志值存储在内存数组中的 array 驱动。或者,Pennant 可以将已解析的特性标志值持久存储在关系数据库中的 database 驱动,这是 Pennant 默认使用的存储机制。

定义特性

要定义一个特性,您可以使用 Feature 外观提供的 define 方法。您需要为特性提供一个名称,以及一个将被调用以解析特性的初始值的闭包。

通常,特性是在服务提供者中使用 Feature 外观定义的。闭包将接收特性检查的 "范围"。最常见的范围是当前经过身份验证的用户。在此示例中,我们将定义一个特性,用于逐步向应用程序的用户推出新的 API:

php
<?php

namespace App\Providers;

use App\Models\User;
use Illuminate\Support\Lottery;
use Illuminate\Support\ServiceProvider;
use Laravel\Pennant\Feature;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Feature::define('new-api', fn (User $user) => match (true) {
            $user->isInternalTeamMember() => true,
            $user->isHighTrafficCustomer() => false,
            default => Lottery::odds(1 / 100),
        });
    }
}

如您所见,我们对此特性有以下规则:

  • 所有内部团队成员都应使用新 API。
  • 任何高流量客户都不应使用新 API。
  • 否则,该特性应随机分配给用户,有 1/100 的机会处于活动状态。

第一次检查 new-api 特性时,闭包的结果将被存储驱动程序存储。下次针对同一用户检查该特性时,该值将从存储中检索,并且不会调用闭包。

为了方便起见,如果特性定义只返回一个彩票,您可以省略闭包:

Feature::define('site-redesign', Lottery::odds(1, 1000));

基于类的特性

Pennant 还允许您定义基于类的特性。与闭包基于特性定义不同,无需在服务提供者中注册基于类的特性。要创建基于类的特性,您可以调用 pennant:feature Artisan 命令。默认情况下,特性类将放置在应用程序的 app/Features 目录中:

shell
php artisan pennant:feature NewApi

编写特性类时,您只需要定义一个 resolve 方法,该方法将被调用以解析给定范围的特性的初始值。同样,范围通常是当前经过身份验证的用户:

php
<?php

namespace App\Features;

use App\Models\User;
use Illuminate\Support\Lottery;

class NewApi
{
    /**
     * Resolve the feature's initial value.
     */
    public function resolve(User $user): mixed
    {
        return match (true) {
            $user->isInternalTeamMember() => true,
            $user->isHighTrafficCustomer() => false,
            default => Lottery::odds(1 / 100),
        };
    }
}

如果您想手动解析基于类的特性的实例,您可以在 Feature 外观上调用 instance 方法:

php
use Illuminate\Support\Facades\Feature;

$instance = Feature::instance(NewApi::class);

NOTE

特性类是通过 容器 解析的,因此当需要时,您可以在特性类的构造函数中注入依赖项。

自定义存储的特性名称

默认情况下,Pennant 将存储特性类的完全限定类名。如果您想将存储的特性名称与应用程序的内部结构解耦,您可以在特性类上指定一个 $name 属性。该属性的值将替换类名存储:

php
<?php

namespace App\Features;

class NewApi
{
    /**
     * The stored name of the feature.
     *
     * @var string
     */
    public $name = 'new-api';

    // ...
}

检查特性

要确定特性是否处于活动状态,您可以使用 Feature 外观上的 active 方法。默认情况下,特性是针对当前经过身份验证的用户进行检查的:

php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Laravel\Pennant\Feature;

class PodcastController
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): Response
    {
        return Feature::active('new-api')
                ? $this->resolveNewApiResponse($request)
                : $this->resolveLegacyApiResponse($request);
    }

    // ...
}

尽管特性默认针对当前经过身份验证的用户进行检查,但您可以轻松地针对另一个用户或 范围 检查该特性。要实现这一点,请使用 Feature 外观提供的 for 方法:

php
return Feature::for($user)->active('new-api')
        ? $this->resolveNewApiResponse($request)
        : $this->resolveLegacyApiResponse($request);

Pennant 还提供了一些其他便捷方法,可能在确定特性是否处于活动状态时非常有用:

php
// Determine if all of the given features are active...
Feature::allAreActive(['new-api', 'site-redesign']);

// Determine if any of the given features are active...
Feature::someAreActive(['new-api', 'site-redesign']);

// Determine if a feature is inactive...
Feature::inactive('new-api');

// Determine if all of the given features are inactive...
Feature::allAreInactive(['new-api', 'site-redesign']);

// Determine if any of the given features are inactive...
Feature::someAreInactive(['new-api', 'site-redesign']);

NOTE

当在 HTTP 上下文之外使用 Pennant 时,例如在 Artisan 命令或排队作业中,您通常应该 显式指定特性的范围。或者,您可以定义一个 默认范围,以适应既有经过身份验证的 HTTP 上下文又有未经身份验证的上下文。

检查基于类的特性

对于基于类的特性,您应该在检查特性时提供类名:

php
<?php

namespace App\Http\Controllers;

use App\Features\NewApi;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Laravel\Pennant\Feature;

class PodcastController
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): Response
    {
        return Feature::active(NewApi::class)
                ? $this->resolveNewApiResponse($request)
                : $this->resolveLegacyApiResponse($request);
    }

    // ...
}

条件执行

when 方法可用于流畅地执行给定的闭包(如果特性处于活动状态)。此外,还可以提供第二个闭包,如果特性处于非活动状态,将执行该闭包:

<?php

namespace App\Http\Controllers;

use App\Features\NewApi;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Laravel\Pennant\Feature;

class PodcastController
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): Response
    {
        return Feature::when(NewApi::class,
            fn () => $this->resolveNewApiResponse($request),
            fn () => $this->resolveLegacyApiResponse($request),
        );
    }

    // ...
}

unless 方法作为 when 方法的逆向,如果特性处于非活动状态,则执行第一个闭包:

return Feature::unless(NewApi::class,
    fn () => $this->resolveLegacyApiResponse($request),
    fn () => $this->resolveNewApiResponse($request),
);

HasFeatures 特性

Pennant 的 HasFeatures 特性可以添加到应用程序的 User 模型(或任何其他具有特性的模型)中,以提供一种流畅、方便的方式来直接从模型中检查特性:

php
<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Pennant\Concerns\HasFeatures;

class User extends Authenticatable
{
    use HasFeatures;

    // ...
}

一旦特性已添加到模型中,您可以通过调用 features 方法轻松检查特性:

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

当然,features 方法提供了访问许多其他便捷方法与特性交互的方式:

php
// Values...
$value = $user->features()->value('purchase-button')
$values = $user->features()->values(['new-api', 'purchase-button']);

// State...
$user->features()->active('new-api');
$user->features()->allAreActive(['new-api', 'server-api']);
$user->features()->someAreActive(['new-api', 'server-api']);

$user->features()->inactive('new-api');
$user->features()->allAreInactive(['new-api', 'server-api']);
$user->features()->someAreInactive(['new-api', 'server-api']);

// Conditional execution...
$user->features()->when('new-api',
    fn () => /* ... */,
    fn () => /* ... */,
);

$user->features()->unless('new-api',
    fn () => /* ... */,
    fn () => /* ... */,
);

Blade 指令

为了使在 Blade 中检查特性成为一种无缝体验,Pennant 提供了一个 @feature 指令:

blade
@feature('site-redesign')
    <!-- 'site-redesign' is active -->
@else
    <!-- 'site-redesign' is inactive -->
@endfeature

中间件

Pennant 还包括一个 中间件,可用于在路由甚至被调用之前验证当前经过身份验证的用户是否有权访问某个特性。您可以将中间件分配给路由并指定访问该路由所需的特性。如果当前经过身份验证的用户的任何指定特性处于非活动状态,路由将返回 400 Bad Request HTTP 响应。可以将多个特性传递给静态 using 方法。

php
use Illuminate\Support\Facades\Route;
use Laravel\Pennant\Middleware\EnsureFeaturesAreActive;

Route::get('/api/servers', function () {
    // ...
})->middleware(EnsureFeaturesAreActive::using('new-api', 'servers-api'));

自定义响应

如果您想自定义中间件在列出的特性之一处于非活动状态时返回的响应,您可以使用 EnsureFeaturesAreActive 中间件提供的 whenInactive 方法。通常,这应该在应用程序的一个服务提供者的 boot 方法中调用:

php
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Laravel\Pennant\Middleware\EnsureFeaturesAreActive;

/**
 * Bootstrap any application services.
 */
public function boot(): void
{
    EnsureFeaturesAreActive::whenInactive(
        function (Request $request, array $features) {
            return new Response(status: 403);
        }
    );

    // ...
}

拦截特性检查

有时在检索给定特性的存储值之前执行一些内存检查会很有用。想象一下,您正在开发一个新的 API,并希望有一种方法可以在不丢失存储中的任何已解析特性值的情况下禁用新 API。如果您在新 API 中发现了一个错误,您可以轻松地为除内部团队成员之外的所有人禁用新 API,修复错误,然后为先前有权访问该特性的用户重新启用新 API。

您可以使用 基于类的特性before 方法来实现这一点。当存在时,before 方法始终在检索存储值之前内存中运行。如果该方法返回非 null 值,它将用于替换特性的存储值,直到请求结束:

php
<?php

namespace App\Features;

use App\Models\User;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Lottery;

class NewApi
{
    /**
     * Run an always-in-memory check before the stored value is retrieved.
     */
    public function before(User $user): mixed
    {
        if (Config::get('features.new-api.disabled')) {
            return $user->isInternalTeamMember();
        }
    }

    /**
     * Resolve the feature's initial value.
     */
    public function resolve(User $user): mixed
    {
        return match (true) {
            $user->isInternalTeamMember() => true,
            $user->isHighTrafficCustomer() => false,
            default => Lottery::odds(1 / 100),
        };
    }
}

您还可以使用此功能来安排全局推出先前处于特性标志后面的特性:

php
<?php

namespace App\Features;

use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Config;

class NewApi
{
    /**
     * Run an always-in-memory check before the stored value is retrieved.
     */
    public function before(User $user): mixed
    {
        if (Config::get('features.new-api.disabled')) {
            return $user->isInternalTeamMember();
        }

        if (Carbon::parse(Config::get('features.new-api.rollout-date'))->isPast()) {
            return true;
        }
    }

    // ...
}

内存缓存

检查特性时,Pennant 会为单个请求创建一个内存缓存的结果。如果您使用的是 database 驱动,这意味着在单个请求中重新检查同一特性标志不会触发额外的数据库查询。这也确保了该特性在请求的持续时间内具有一致的结果。

如果您需要手动刷新内存缓存,您可以使用 Feature 外观提供的 flushCache 方法:

Feature::flushCache();

范围

指定范围

如前所述,特性通常是针对当前经过身份验证的用户进行检查的。但是,这并不总是符合您的需求。因此,可以通过 Feature 外观的 for 方法指定要针对给定特性检查的范围:

php
return Feature::for($user)->active('new-api')
        ? $this->resolveNewApiResponse($request)
        : $this->resolveLegacyApiResponse($request);

当然,特性范围不仅限于 "用户"。想象一下,您已经构建了一个新的计费体验,并且您正在逐步向整个团队而不是单个用户推出它。也许您希望较旧的团队比较新的团队有较慢的推出速度。您的特性解析闭包可能如下所示:

php
use App\Models\Team;
use Carbon\Carbon;
use Illuminate\Support\Lottery;
use Laravel\Pennant\Feature;

Feature::define('billing-v2', function (Team $team) {
    if ($team->created_at->isAfter(new Carbon('1st Jan, 2023'))) {
        return true;
    }

    if ($team->created_at->isAfter(new Carbon('1st Jan, 2019'))) {
        return Lottery::odds(1 / 100);
    }

    return Lottery::odds(1 / 1000);
});

您会注意到我们定义的闭包不期望 User,而是期望 Team 模型。要确定此特性是否对用户的团队处于活动状态,您应该将团队传递给 Feature 外观的 for 方法:

php
if (Feature::for($user->team)->active('billing-v2')) {
    return redirect('/billing/v2');
}

// ...

默认范围

还可以自定义 Pennant 用于检查特性的默认范围。例如,也许所有特性都是针对当前经过身份验证的用户的团队而不是用户进行检查的。而不是每次检查特性时都调用 Feature::for($user->team),您可以将团队指定为默认范围。通常,这应该在应用程序的一个服务提供者中完成:

php
<?php

namespace App\Providers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\ServiceProvider;
use Laravel\Pennant\Feature;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Feature::resolveScopeUsing(fn ($driver) => Auth::user()?->team);

        // ...
    }
}

如果未通过 for 方法显式提供范围,特性检查现在将使用当前经过身份验证的用户的团队作为默认范围:

php
Feature::active('billing-v2');

// Is now equivalent to...

Feature::for($user->team)->active('billing-v2');

可空范围

如果您提供的范围是 null,并且特性的定义不支持 null(通过包含可空类型或包含 null 的联合类型),Pennant 将自动返回 false 作为特性的结果值。

因此,如果您正在检查的特性的范围可能是 null,并且您希望特性的值解析器被调用,您应该在特性的定义逻辑中处理 null 范围值。null 范围可能会在 Artisan 命令、排队作业或未经身份验证的路由中发生,因为通常在这些上下文中没有经过身份验证的用户。如果您没有始终 显式指定特性范围,则应确保范围的类型是 "可空的",并在特性定义逻辑中处理 null 范围值:

php
use App\Models\User;
use Illuminate\Support\Lottery;
use Laravel\Pennant\Feature;

Feature::define('new-api', fn (User $user) => match (true) {// [tl! remove]
Feature::define('new-api', fn (User|null $user) => match (true) {// [tl! add]
    $user === null => true,// [tl! add]
    $user->isInternalTeamMember() => true,
    $user->isHighTrafficCustomer() => false,
    default => Lottery::odds(1 / 100),
});

识别范围

Pennant 的内置 arraydatabase 存储驱动知道如何为所有 PHP 数据类型以及 Eloquent 模型正确存储范围标识符。但是,如果您的应用程序使用第三方 Pennant 驱动,该驱动可能不知道如何为您的应用程序中的 Eloquent 模型或其他自定义类型正确存储标识符。

鉴于此,Pennant 允许您通过在应用程序中用作 Pennant 范围的对象上实现 FeatureScopeable 契约来格式化范围值以供存储。

例如,想象一下您在单个应用程序中使用两个不同的特性驱动:内置的 database 驱动和第三方 "Flag Rocket" 驱动。"Flag Rocket" 驱动不知道如何正确存储 Eloquent 模型。相反,它需要一个 FlagRocketUser 实例。通过在应用程序中用作 Pennant 范围的对象上实现 FeatureScopeable 契约定义的 toFeatureIdentifier 方法,我们可以自定义每个驱动用于我们应用程序的范围值:

php
<?php

namespace App\Models;

use FlagRocket\FlagRocketUser;
use Illuminate\Database\Eloquent\Model;
use Laravel\Pennant\Contracts\FeatureScopeable;

class User extends Model implements FeatureScopeable
{
    /**
     * Cast the object to a feature scope identifier for the given driver.
     */
    public function toFeatureIdentifier(string $driver): mixed
    {
        return match($driver) {
            'database' => $this,
            'flag-rocket' => FlagRocketUser::fromId($this->flag_rocket_id),
        };
    }
}

序列化范围

默认情况下,Pennant 会在存储与 Eloquent 模型相关联的特性时使用完全限定类名。如果您已经在服务提供者中使用了 Eloquent 多态映射,您可以选择让 Pennant 也使用多态映射来解耦存储的特性与应用程序结构。

要实现这一点,在定义 Eloquent 多态映射的服务提供者中调用 Feature 外观的 useMorphMap 方法后,您可以调用该方法:

php
use Illuminate\Database\Eloquent\Relations\Relation;
use Laravel\Pennant\Feature;

Relation::enforceMorphMap([
    'post' => 'App\Models\Post',
    'video' => 'App\Models\Video',
]);

Feature::useMorphMap();

丰富特性值

到目前为止,我们主要展示了特性处于二进制状态,这意味着它们要么是 "活动" 的,要么是 "非活动" 的,但 Pennant 还允许您存储丰富的值。

例如,想象一下您正在测试应用程序 "购买现在" 按钮的三种新颜色。您可以从特性定义中返回字符串而不是 truefalse:

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

Feature::define('purchase-button', fn (User $user) => Arr::random([
    'blue-sapphire',
    'seafoam-green',
    'tart-orange',
]));

您可以使用 value 方法检索 purchase-button 特性的值:

php
$color = Feature::value('purchase-button');

Pennant 的包含 Blade 指令还可以轻松地根据特性的当前值有条件地呈现内容:

blade
@feature('purchase-button', 'blue-sapphire')
    <!-- 'blue-sapphire' is active -->
@elsefeature('purchase-button', 'seafoam-green')
    <!-- 'seafoam-green' is active -->
@elsefeature('purchase-button', 'tart-orange')
    <!-- 'tart-orange' is active -->
@endfeature

NOTE

使用丰富值时,重要的是要知道当特性有任何值而不是 false 时,该特性就被视为 "活动"。

调用 条件 when 方法时,特性的丰富值将提供给第一个闭包:

Feature::when('purchase-button',
    fn ($color) => /* ... */,
    fn () => /* ... */,
);

同样,调用条件 unless 方法时,特性的丰富值将提供给可选的第二个闭包:

Feature::unless('purchase-button',
    fn () => /* ... */,
    fn ($color) => /* ... */,
);

检索多个特性

values 方法允许检索给定范围的多个特性的值:

php
Feature::values(['billing-v2', 'purchase-button']);

// [
//     'billing-v2' => false,
//     'purchase-button' => 'blue-sapphire',
// ]

或者,您可以使用 all 方法检索给定范围的所有定义特性的值:

php
Feature::all();

// [
//     'billing-v2' => false,
//     'purchase-button' => 'blue-sapphire',
//     'site-redesign' => true,
// ]

但是,基于类的特性是动态注册的,Pennant 在当前请求中尚未检查这些特性时不会知道它们。这意味着如果您的应用程序的基于类的特性尚未在当前请求中检查,它们可能不会出现在 all 方法返回的结果中。

如果您希望确保基于类的特性始终包含在使用 all 方法时,您可以使用 Pennant 的特性发现功能。要开始使用,在应用程序的一个服务提供者中调用 discover 方法:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Laravel\Pennant\Feature;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Feature::discover();

        // ...
    }
}

discover 方法将注册应用程序 app/Features 目录中的所有特性类。all 方法现在将包含这些类,而不考虑它们是否已在当前请求中检查:

php
Feature::all();

// [
//     'App\Features\NewApi' => true,
//     'billing-v2' => false,
//     'purchase-button' => 'blue-sapphire',
//     'site-redesign' => true,
// ]

预加载

尽管 Pennant 为单个请求保留了所有已解析特性的内存缓存,但仍然可能遇到性能问题。为了缓解这一问题,Pennant 提供了预加载特性值的能力。

为了说明这一点,想象一下我们在循环中检查特性是否处于活动状态:

php
use Laravel\Pennant\Feature;

foreach ($users as $user) {
    if (Feature::for($user)->active('notifications-beta')) {
        $user->notify(new RegistrationSuccess);
    }
}

假设我们使用的是数据库驱动,此代码将为循环中的每个用户执行数据库查询 - 可能会执行数百个查询。但是,使用 Pennant 的 load 方法,我们可以通过预加载一组用户或范围的特性值来消除此潜在的性能瓶颈:

php
Feature::for($users)->load(['notifications-beta']);

foreach ($users as $user) {
    if (Feature::for($user)->active('notifications-beta')) {
        $user->notify(new RegistrationSuccess);
    }
}

要仅在特征值尚未加载时加载它们,可以使用 loadMissing 方法:

php
Feature::for($users)->loadMissing([
    'new-api',
    'purchase-button',
    'notifications-beta',
]);

您可以使用 loadAll 方法加载所有定义的特征:

php
Feature::for($user)->loadAll();

更新值

当特征的值首次解析时,底层驱动程序会将结果存储在存储中。这通常是确保用户在请求之间获得一致体验所必需的。然而,有时您可能希望手动更新特征的存储值。

为此,您可以使用 activatedeactivate 方法来切换特征的"开"或"关"状态:

php
use Laravel\Pennant\Feature;

// 为默认范围激活特征...
Feature::activate('new-api');

// 为给定范围停用特征...
Feature::for($user->team)->deactivate('billing-v2');

您还可以通过向 activate 方法提供第二个参数来手动设置特征的丰富值:

php
Feature::activate('purchase-button', 'seafoam-green');

要指示 Pennant 忘记特征的存储值,您可以使用 forget 方法。当再次检查特征时,Pennant 将根据其特征定义解析特征的值:

php
Feature::forget('purchase-button');

批量更新

要批量更新存储的特征值,您可以使用 activateForEveryonedeactivateForEveryone 方法。

例如,假设您现在对 new-api 特征的稳定性充满信心,并且已经确定了最佳的 'purchase-button' 颜色以供结账流程使用 - 您可以相应地更新所有用户的存储值:

php
use Laravel\Pennant\Feature;

Feature::activateForEveryone('new-api');

Feature::activateForEveryone('purchase-button', 'seafoam-green');

或者,您可以为所有用户停用特征:

php
Feature::deactivateForEveryone('new-api');

NOTE

这只会更新由 Pennant 的存储驱动程序存储的已解析特征值。您还需要在应用程序中更新特征定义。

清除特征

有时,清除存储中的整个特征是有用的。如果您已从应用程序中删除特征,或者您对特征定义进行了调整,希望将其推广到所有用户,这通常是必要的。

您可以使用 purge 方法删除特征的所有存储值:

php
// 清除单个特征...
Feature::purge('new-api');

// 清除多个特征...
Feature::purge(['new-api', 'purchase-button']);

如果您希望清除 所有 特征,可以在不带任何参数的情况下调用 purge 方法:

php
Feature::purge();

由于在应用程序的部署管道中清除特征可能很有用,Pennant 包含一个 pennant:purge Artisan 命令,该命令将从存储中清除提供的特征:

sh
php artisan pennant:purge new-api

php artisan pennant:purge new-api purchase-button

您还可以清除所有特征 除了 给定特征列表中的特征。例如,假设您希望清除所有特征,但保留存储中"new-api"和"purchase-button"特征的值。为此,您可以将这些特征名称传递给 --except 选项:

sh
php artisan pennant:purge --except=new-api --except=purchase-button

为了方便,pennant:purge 命令还支持 --except-registered 标志。此标志表示应清除所有特征,除了在服务提供者中显式注册的特征:

sh
php artisan pennant:purge --except-registered

测试

在测试与特征标志交互的代码时,控制特征标志返回值的最简单方法是简单地重新定义特征。例如,假设您在应用程序的某个服务提供者中定义了以下特征:

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

Feature::define('purchase-button', fn () => Arr::random([
    'blue-sapphire',
    'seafoam-green',
    'tart-orange',
]));

要在测试中修改特征的返回值,您可以在测试开始时重新定义特征。以下测试将始终通过,即使 Arr::random() 实现仍然存在于服务提供者中:

php
use Laravel\Pennant\Feature;

test('it can control feature values', function () {
    Feature::define('purchase-button', 'seafoam-green');

    expect(Feature::value('purchase-button'))->toBe('seafoam-green');
});
php
use Laravel\Pennant\Feature;

public function test_it_can_control_feature_values()
{
    Feature::define('purchase-button', 'seafoam-green');

    $this->assertSame('seafoam-green', Feature::value('purchase-button'));
}

对于基于类的特征,也可以使用相同的方法:

php
use Laravel\Pennant\Feature;

test('it can control feature values', function () {
    Feature::define(NewApi::class, true);

    expect(Feature::value(NewApi::class))->toBeTrue();
});
php
use App\Features\NewApi;
use Laravel\Pennant\Feature;

public function test_it_can_control_feature_values()
{
    Feature::define(NewApi::class, true);

    $this->assertTrue(Feature::value(NewApi::class));
}

如果您的特征返回 Lottery 实例,则有一些有用的 测试助手可用

存储配置

您可以通过在应用程序的 phpunit.xml 文件中定义 PENNANT_STORE 环境变量来配置 Pennant 在测试期间使用的存储:

xml
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true">
    <!-- ... -->
    <php>
        <env name="PENNANT_STORE" value="array"/>
        <!-- ... -->
    </php>
</phpunit>

添加自定义 Pennant 驱动程序

实现驱动程序

如果 Pennant 的现有存储驱动程序都不符合您的应用程序需求,您可以编写自己的存储驱动程序。您的自定义驱动程序应实现 Laravel\Pennant\Contracts\Driver 接口:

php
<?php

namespace App\Extensions;

use Laravel\Pennant\Contracts\Driver;

class RedisFeatureDriver implements Driver
{
    public function define(string $feature, callable $resolver): void {}
    public function defined(): array {}
    public function getAll(array $features): array {}
    public function get(string $feature, mixed $scope): mixed {}
    public function set(string $feature, mixed $scope, mixed $value): void {}
    public function setForAllScopes(string $feature, mixed $value): void {}
    public function delete(string $feature, mixed $scope): void {}
    public function purge(array|null $features): void {}
}

现在,我们只需使用 Redis 连接实现每个方法。有关如何实现每个方法的示例,请查看 Pennant 源代码 中的 Laravel\Pennant\Drivers\DatabaseDriver

NOTE

Laravel 不会随附用于容纳您的扩展的目录。您可以将它们放置在您喜欢的任何位置。在此示例中,我们创建了一个 Extensions 目录来容纳 RedisFeatureDriver

注册驱动程序

实现驱动程序后,您可以准备将其注册到 Laravel。要向 Pennant 添加其他驱动程序,您可以使用 Feature facade 提供的 extend 方法。您应该在应用程序的 服务提供者boot 方法中调用 extend 方法:

php
<?php

namespace App\Providers;

use App\Extensions\RedisFeatureDriver;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use Laravel\Pennant\Feature;

class AppServiceProvider extends ServiceProvider
{
    /**
     * 注册任何应用程序服务。
     */
    public function register(): void
    {
        // ...
    }

    /**
     * 启动任何应用程序服务。
     */
    public function boot(): void
    {
        Feature::extend('redis', function (Application $app) {
            return new RedisFeatureDriver($app->make('redis'), $app->make('events'), []);
        });
    }
}

驱动程序注册后,您可以在应用程序的 config/pennant.php 配置文件中使用 redis 驱动程序:

'stores' => [

    'redis' => [
        'driver' => 'redis',
        'connection' => null,
    ],

    // ...

],

事件

Pennant 触发多种事件,这在跟踪应用程序中的特征标志时非常有用。

Laravel\Pennant\Events\FeatureRetrieved

每当 检查特征 时,都会触发此事件。此事件对于创建和跟踪特征标志在应用程序中的使用情况指标可能很有用。

Laravel\Pennant\Events\FeatureResolved

此事件在特定范围内首次解析特征的值时触发。

Laravel\Pennant\Events\UnknownFeatureResolved

此事件在特定范围内首次解析未知特征时触发。如果您打算删除特征标志,但不小心在应用程序中留下了零散的引用,监听此事件可能会很有用:

php
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Laravel\Pennant\Events\UnknownFeatureResolved;

class AppServiceProvider extends ServiceProvider
{
    /**
     * 启动任何应用程序服务。
     */
    public function boot(): void
    {
        Event::listen(function (UnknownFeatureResolved $event) {
            Log::error("Resolving unknown feature [{$event->feature}].");
        });
    }
}

Laravel\Pennant\Events\DynamicallyRegisteringFeatureClass

当在请求期间首次动态检查 基于类的特征 时,会触发此事件。

Laravel\Pennant\Events\UnexpectedNullScopeEncountered

当将 null 范围传递给不支持 null 的特征定义时,会触发此事件 (#nullable-scope)

这种情况会被优雅地处理,特征将返回 false。但是,如果您希望选择退出此特征的默认优雅行为,您可以在应用程序的 AppServiceProviderboot 方法中注册一个监听器:

php
use Illuminate\Support\Facades\Log;
use Laravel\Pennant\Events\UnexpectedNullScopeEncountered;

/**
 * 启动任何应用程序服务。
 */
public function boot(): void
{
    Event::listen(UnexpectedNullScopeEncountered::class, fn () => abort(500));
}

Laravel\Pennant\Events\FeatureUpdated

此事件在为范围更新特征时触发,通常通过调用 activatedeactivate

Laravel\Pennant\Events\FeatureUpdatedForAllScopes

此事件在为所有范围更新特征时触发,通常通过调用 activateForEveryonedeactivateForEveryone

Laravel\Pennant\Events\FeatureDeleted

此事件在为范围删除特征时触发,通常通过调用 forget

Laravel\Pennant\Events\FeaturesPurged

此事件在清除特定特征时触发。

Laravel\Pennant\Events\AllFeaturesPurged

此事件在清除所有特征时触发。