bazo/feature-toggler

PHP 功能切换库

dev-master 2016-07-07 11:19 UTC

This package is not auto-updated.

Last update: 2024-09-14 15:58:09 UTC


README

PHP 功能切换库

使用方法

$toggler = new Toggler($config);
if($toggler->enabled('featureName')) {
	...
}

您还可以向切换器传递上下文

$toggler = new Toggler($config);

$context = [
	'userId' => 150,
	'site' => 'sk'

];
//using only globals
if($toggler->enabled('feature1')) { //true
	...
}

or
//using globals and local context
if($toggler->enabled('feature1', $context)) { //true
	...
}

配置

简单,使用数组

$config = [
		'globals' => [
			'site'=> 'sk'
		],
		'feature1' => [
			'conditions' => [
				['field' => 'site', 'operator' => 'in', 'arg' => ['sk', 'cz']],
				['field' => 'userId', 'operator' => '>', 'arg' => 140]
		],
		'paypal' => [
			'conditions' => [
				['field' => 'site', 'operator' => 'in', 'arg' => ['sk', 'cz', 'de', 'at']]
			]
		]
];

或者您可以使用简写语法来表示条件,这使得代码更简洁、更易读

['site', 'in', ['sk', 'cz', 'de', 'at']]

操作符

有5个内置操作符,不能被覆盖:> - 值必须大于参数 < - 值必须小于参数 = - 值必须等于参数 in - 值必须在参数集合中 notIn - 值必须在参数集合之外

您还可以注册自定义操作符。自定义操作符必须实现 IOperator 接口

$operator = new MyCustomOperator;
$toggler->registerOperator($operator);

您还可以覆盖默认操作符符号

$toggler->registerOperator($operator, 'myCustomSign');

然后您可以这样写条件

['field' => 'site', 'operator' => 'myCustomSign', 'arg' => [1, 2, 3, ...]]

自定义功能后端

您还可以为存储功能和它们的条件使用自定义后端,例如数据库

后端需要实现 IFeaturesBackend 接口,该接口有一个方法: getConfig()

然后您可以使用它这样

$backend = new MyRedisBackend(...);
$toggler = new BackendDrivenToggler($backend)

祝您使用愉快!