mileschou/toggle-simplify

PHP 的简化功能开关库

v2.0.0 2021-03-24 17:03 UTC

This package is auto-updated.

Last update: 2024-08-25 04:40:01 UTC


README

Testing codecov Codacy Badge Latest Stable Version Total Downloads License

PHP 的简化功能开关库

概念

即将推出...

用法

只需一个文件!使用 Toggle 做所有事情。

功能开关

使用固定结果

<?php

$toggle = new Toggle();
$toggle->create('f1', true);

// Will return true
$toggle->isActive('f1');

使用可调用函数动态决定返回值

<?php

$toggle = new Toggle();
$toggle->create('f1', function() {
    return true;
});

// Will return true
$toggle->isActive('f1');

使用带上下文的可调用函数

<?php

$toggle = new Toggle();
$toggle->create('f1', function($context) {
    return $context['default'];
});

// Will return true
$toggle->isActive('f1', [
    'return' => true,
]);

参数

Feature 实例可以存储一些参数。例如

<?php

$toggle = new Toggle();

$toggle->create('f1', true, ['name' => 'Miles']);
$toggle->create('f2', false, ['name' => 'Chou']);

// Will return 'Chou'
$toggle->params('f1', 'name');

// Also using in callback
$toggle->create('f3', function($context, array $params) {
    return $params['key'] === $context['key'];
}, ['key' => 'foo']);

导出 / 导入结果

当你想将结果持久化到某些存储时,我们可以使用 result() 方法。

<?php

$toggle = new Toggle();

$toggle->create('f1', true);
$toggle->create('f2', false);

$result = $toggle->result(); // array ['f1' => true, 'f2' => false]

此外,你也可以恢复结果。

<?php

$toggle = new Toggle();

$toggle->create('f1', false);
$toggle->create('f2', true);
$toggle->result(['f1' => true, 'f2' => false]);

$toggle->isActive('f1'); // true
$toggle->isActive('f2'); // false

控制结构

这个片段类似于 if / switch 结构

<?php

$toggle = new Toggle();
$toggle->create('f1');
$toggle->create('f2');
$toggle->create('f3');

$toggle
    ->when('f1', function ($context, $params) {
        // Something when f1 is on
    })
    ->when('f2', function ($context, $params) {
        // Something when f2 is on
    })
    ->when('f3', function ($context, $params) {
        // Something when f3 is on
    });