stogon/unleash-bundle 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

stogon/unleash-bundle

Composer 安装命令:

composer require stogon/unleash-bundle

包简介

Unleash SDK implementation for Symfony framework

README 文档

README

Packagist PHP from Packagist License codecov

An Unleash bundle for Symfony 6.4+ and 7.4+ applications.

This provide an easy way to implement feature flags using Gitlab Feature Flags Feature.

This implementation conforms to the official Unleash standards.

Inspired by minds/unleash-client-php and mikefrancis/laravel-unleash.

Installation

composer require stogon/unleash-bundle

Configurations

Full configurations example:

# config/packages/unleash.yaml
unleash:
    # The full URL to your unleash-server instance (must end with a slash).
    # Example with the "feature_flags" feature from Gitlab.com : https://gitlab.com/api/v4/feature_flags/unleash/<project_id>/
    api_url: 'https://gitlab.com/api/v4/feature_flags/unleash/<project_id>/'

    # Authorization key if needed
    auth_token: '<auth>'

    # Instance ID of your unleash application.
    # Example : VPQgqIdAxQyXY96d6oWj
    instance_id: '<some ID>'

    # Unleash application name.
    # For Gitlab feature flags, it can be set to the environment name.
    # default: '%kernel.environment%'
    environment: '%kernel.environment%'

    cache:
        # Enable caching of features fetched from Unleash server.
        # default: true
        enabled: true
        # Service ID to use for caching (must be a cache pool)
        # default: '%unleach.cache.service%' (which resolve to '@cache.unleash.strategies' service)
        service: '@cache.app'
        # The period of time from the present after which the item MUST be considered expired in the cache in seconds
        # default: 15
        ttl: 15

Usage

To use the client, simply inject Stogon\UnleashBundle\UnleashInterface into your service and use it like this:

<?php

namespace App\Controller;

use Stogon\UnleashBundle\UnleashInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class HomeController extends AbstractController
{
    #[Route('/', name: 'homepage')]
    public function index(UnleashInterface $unleash): Response
    {
        if ($unleash->isFeatureEnabled('my_awesome_feature')) {
            // do something awesome !
        }

        if ($unleash->isFeatureDisabled('my_other_feature')) {
            // do something else
        }

        return $this->render('home/index.html.twig');
    }
}

Twig

The bundle also provide Twig functions to check if a feature is enabled/disabled for the current user:

{# Check if a feature is enabled for current user #}
{%- if is_feature_enabled('my_awesome_feature') -%}
    <div class="alert alert-success" role="alert">
        The <code>my_awesome_feature</code> feature is enabled for current user !
    </div>
{%- else -%}
    <div class="alert alert-warning" role="alert">
        The <code>my_awesome_feature</code> feature is disabled for current user !
    </div>
{%- endif -%}

{# Check if a feature is disabled for current user #}
{%- if is_feature_disabled('my_awesome_feature') -%}
    <div class="alert alert-success" role="alert">
        The <code>my_awesome_feature</code> feature is disabled for current user !
    </div>
{%- else -%}
    <div class="alert alert-warning" role="alert">
        The <code>my_awesome_feature</code> feature is enabled for current user !
    </div>
{%- endif -%}

Console

There are console commands that comes with this bundle :

Command name Description
unleash:features:fetch Fetch Unleash features from remote and store them in the cache for later usage.
unleash:features:list List available Unleash features from remote.

Strategies

Available strategies:

Strategy name Description
default It is the simplest activation strategy and basically means "active for everyone".
userWithId This strategy allows you to specify a list of user IDs that you want to expose the new feature for. (A user id may, of course, be an email if that is more appropriate in your system.)
flexibleRollout A flexible rollout strategy which combines all gradual rollout strategies in to a single strategy (and will in time replace them)
gradualRolloutUserId The gradualRolloutUserId strategy gradually activates a feature toggle for logged-in users. Stickiness is based on the user ID. The strategy guarantees that the same user gets the same experience every time across devices
gradualRolloutSessionId Similar to gradualRolloutUserId strategy, this strategy gradually activates a feature toggle, with the exception being that the stickiness is based on the session IDs. This makes it possible to target all users (not just logged-in users), guaranteeing that a user will get the same experience within a session.
gradualRolloutRandom The gradualRolloutRandom strategy randomly activates a feature toggle and has no stickiness. We have found this rollout strategy very useful in some scenarios, especially when we enable a feature which is not visible to the user. It is also the strategy we use to sample metrics and error reports.

For more informations, see https://docs.getunleash.io/docs/activation_strategy

Add a custom strategy

If the existing strategies does not fill your needs, you can implement a custom strategy with your own logic.

First, you need to create a class which implements the Stogon\UnleashBundle\Strategy\StrategyInterface

<?php

namespace App\Unleash\Strategy;

use Stogon\UnleashBundle\Strategy\StrategyInterface;

class MyCustomStrategy implements StrategyInterface
{
    public function isEnabled(array $parameters = [], array $context = [], mixed ...$args): bool
    {
        // TODO: Implement your custom logic here.

        return false;
    }
}

Then you need to tag your custom strategy with the unleash.strategy tag and provide a activation_name for it.

services:
    App\Unleash\Strategy\MyCustomStrategy:
        tags:
            - { name: unleash.strategy, activation_name: my_custom_activation_strategy }

The activation_name must match the strategy.name value of your Unleash strategy ! see https://docs.getunleash.io/docs/activation_strategy

Override an existing strategy

You can override an existing strategy simply by setting the activation_name of the tag to the same strategy name used here.

Example:

services:
    App\Unleash\Strategy\MyCustomStrategy:
        tags:
            - { name: unleash.strategy, activation_name: userWithId }

Add additional context to strategies

If you want to add additional data to the context passed to resolved strategy ($context parameter of the Stogon\UnleashBundle\Strategy\StrategyInterface::isEnabled method), you can implement an event listener/subscriber to react to the Stogon\UnleashBundle\Event\UnleashContextEvent event.

Example:

<?php

namespace App\EventSubscriber;

use Stogon\UnleashBundle\Event\UnleashContextEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class UnleashContextSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            UnleashContextEvent::class => ['onUnleashContextEvent'],
        ];
    }

    public function onUnleashContextEvent(UnleashContextEvent $event): void
    {
        // Get the original payload as an array;
        $payload = $event->getPayload();

        // Set some custom data
        $payload['awesome_data'] = 'amazing';

        // Update payload
        $event->setPayload($payload);
    }
}

Testing

Simply run :

composer run test

or

$ ./vendor/bin/phpunit
$ ./vendor/bin/phpstan analyse
$ ./vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.dist.php

Contributing

See CONTRIBUTING.md.

stogon/unleash-bundle 适用场景与选型建议

stogon/unleash-bundle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 78.55k 次下载、GitHub Stars 达 12, 最近一次更新时间为 2021 年 05 月 02 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「symfony」 「bundle」 「feature-flags」 「unleash」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 stogon/unleash-bundle 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 stogon/unleash-bundle 我们能提供哪些服务?
定制开发 / 二次开发

基于 stogon/unleash-bundle 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 78.55k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 12
  • 点击次数: 16
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 12
  • Watchers: 3
  • Forks: 7
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-05-02