xepozz / feature-flag
此包的最新版本(1.0.0)没有可用的许可信息。
Yii 3 特性标志管理系统
1.0.0
2023-07-28 21:23 UTC
Requires
- php: ^8.1
- yiisoft/yii-http: ^1.0.3
Requires (Dev)
- phpunit/phpunit: 10.0.17
- vimeo/psalm: ^5.8
- yiisoft/yii-debug: dev-master
Suggests
- ext-redis: Using Redis as a storage for feature flags
- yiisoft/yii-debug: Debugging of feature flags
This package is auto-updated.
Last update: 2024-08-29 00:05:22 UTC
README
这是一个简单的库,可以根据一组规则启用/禁用功能。
安装
composer require xepozz/feature-flag
配置
选择您想使用的驱动程序。当前,该库支持以下驱动程序
- InMemory - 在内存中存储数据。此驱动程序是默认使用的。
- Redis - 在 Redis 中存储数据。使用 phpredis 扩展
InMemory
在依赖注入容器配置文件中配置驱动程序
di.php
\Xepozz\FeatureFlag\Driver\InMemoryDriver::class => [ '__construct()' => [ 'flags' => [ 155 => false, 'feature_name' => true, FeaturesEnum::FEATURE_NAME => true, ], ], ],
或者使用 params.php
'xepozz/feature-flag' => [ 'flags' => [ 155 => false, 'feature_name' => true, FeaturesEnum::FEATURE_NAME => true, ], ],
使用
params.php
配置驱动程序仅适用于InMemoryDriver
。
Redis
在依赖注入容器配置文件中配置驱动程序
di.php
\Xepozz\FeatureFlag\Driver\RedisDriver::class => function () { $redis = new Redis(); $redis->pconnect( host: '127.0.0.1', port: 6379, timeout: 2.5, ); return new \Xepozz\FeatureFlag\Driver\RedisDriver(redis: $redis, hashTableKey: 'ab'); },
驱动程序使用散列表函数来存储和检索数据。更多关于散列表函数的信息请参见 此处。
选择驱动程序
选择驱动程序后,您需要配置依赖注入容器
di.php
use Xepozz\FeatureFlag\FlagStorageInterface; use \Xepozz\FeatureFlag\Driver\RedisDriver; return [ // ... FlagStorageInterface::class => RedisDriver::class, // ... ]
用法
从依赖注入容器中获取 \Xepozz\FeatureFlag\FlagStorageInterface
并使用它
isActive(string|int|BackedEnum $flag): bool
use Xepozz\FeatureFlag\FlagStorageInterface; class Controller { public function index(FlagStorageInterface $flagStorage) { if ($flagStorage->isActive('feature_name')) { // feature is enabled } else { // feature is disabled } } }
setFlag(string|int|BackedEnum $flag, bool $active): void
请注意,如果您不使用
InMemoryDriver
,标志将被永久存储。
如果使用
InMemoryDriver
,标志将仅存储在当前请求中。因此,您可以根据代码中的条件切换标志。例如,您可以为受信任的 IP 地址启用功能。
use Xepozz\FeatureFlag\FlagStorageInterface; class Controller { public function index(FlagStorageInterface $flagStorage) { if ($condition) { $flagStorage->setFlag('feature_name', true); } } }
getAll(): array
返回所有标志的关联数组 array<string, bool>
。
只有 InMemoryDriver
支持将 BackendEnum
作为键返回,因为它不需要序列化键。
键是标志名称,值是标志状态。
use Xepozz\FeatureFlag\FlagStorageInterface; class Controller { public function index(FlagStorageInterface $flagStorage) { $flags = $flagStorage->getAll(); // ... } }
测试
Redis
Redis 驱动程序需要 phpredis 扩展 和正在运行的 Redis 服务器。
您可以使用以下命令在 Docker 容器中启动 Redis 服务器
docker run --rm -p 6379:6379 redis
或者使用 docker-compose
docker-compose up -d
运行测试
composer test
或者
./vendor/bin/phpunit
寻找更多模块?
- Unique ID - 允许您跟踪应用程序中的唯一用户。
- Request ID - 用于跟踪目的的简单库,用于生成唯一的请求和响应 ID。
- AB - 一个简单的库,可以根据一组规则启用 A/B 测试。
- Shortcut - 用于快速开发 Yii 3 应用程序的辅助函数集合。