markstory / cakephp-feature-flags
CakePHP 功能标志插件
dev-main
2024-09-03 04:10 UTC
Requires
- php: >=8.1
- cakephp/cakephp: ^5.0.1
Requires (Dev)
- cakephp/cakephp-codesniffer: ~5.1.0
- phpunit/phpunit: ^10.1
This package is auto-updated.
Last update: 2024-09-03 04:12:44 UTC
README
FeatureFlags 是一个 CakePHP 插件,允许您在应用程序中使用功能标志来根据简单的应用程序配置或更复杂的基于规则的系统启用功能。
通过使用功能标志,您可以分离代码部署与启用功能之间的关系,或者在不同的环境中启用不同的功能。例如,您可能有一些不完整的功能,在预发布环境中启用但在生产环境中禁用。
安装
您可以使用 composer 将此插件安装到您的应用程序中。
安装 composer 包的推荐方法是
composer require markstory/cakephp-feature-flags
接下来,运行以下命令来加载插件
bin/cake plugin load FeatureFlags
用法
首先,您需要决定您想要简单的布尔功能标志,还是更复杂基于规则的标志。以下示例中,我们假设您有两个功能(calendar-v2
和 checkout-v2
)想要有条件地启用。
简单功能标志
首先创建一个配置文件 config/features.php
,内容如下
<?php return [ 'Features' => [ 'calendar-v2' => true, 'checkout-v2' => false, ], ];
在您的 Application::services()
方法中添加以下代码
use FeatureFlags\FeatureManagerInterface; use FeatureFlags\Simple\FeatureManager; public function services(ContainerInterface $container): void { $container->addShared(FeatureManagerInterface::class, function () { return new FeatureManager(Configure::read('Features')); }); }
配置 DI 容器后,您可以将 FeatureManager
注入到控制器和命令中,根据需要。
public function view(FeatureManagerInterface $features, $id) { if ($features->has('calendar-v2')) { // Logic for the new feature. return $this->render(); } ... }
基于规则的标志
首先创建一个配置文件 config/features.php
,内容如下
<?php return [ 'Features' => [ // Each key is a feature name 'calendar-v2' => [ // Features are composed of many segments. // All conditions in a segment must match for a feature to be // granted 'segments' => [ // Segments can incrementally enable features 'rollout' => 50, // Segments are composed of multiple conditions 'conditions' => [ [ 'property' => 'user_email', 'op' => 'equal', 'value' => 'winner@example.com', ] ], ], ], ], ];
在您的 Application::services()
方法中添加以下代码
use FeatureFlags\FeatureManagerInterface; use FeatureFlags\RuleBased\FeatureManager; public function services(ContainerInterface $container): void { $container->addShared(FeatureManagerInterface::class, function () { return new FeatureManager( function (array $data) { $context = []; // Add properties to `$context` based on the data you use // to check features. return $context; } Configure::read('Features') ); }); }
配置 DI 容器后,您可以将 FeatureManager
注入到控制器和命令中,根据需要。
public function view(FeatureManagerInterface $features, $id) { // Including application data in `features->has` calls allows // you to build custom feature logic that fits your application. $identity = $this->request->getAttribute('identity'); if ($features->has('calendar-v2', ['user' => $identity])) { // Logic for the new feature. return $this->render(); } ... }
编写条件
条件将安全地从您的应用程序准备的 context
中提取键。每个条件将您的 context
中的单个属性与已知值进行比较。
[ 'property' => 'user_email', 'op' => 'equal', 'value' => 'winner@example.com', ]
以下 op
值受到支持
equal
如果上下文值匹配value
,则匹配not_equal
如果上下文值不等于value
,则匹配in
如果上下文值在value
的数组中,则匹配not_in
如果上下文值不在value
的数组中,则匹配