codingpaws/gitlab-feature

在您的Laravel应用中使用GitLab功能标志

1.6 2022-08-19 14:20 UTC

This package is auto-updated.

Last update: 2024-09-19 18:59:39 UTC


README

在您的Laravel应用中使用GitLab 功能标志

入门指南

  1. 在GitLab实例中的项目中设置功能标志。
  2. 在您的项目中安装此库。

    composer require codingpaws/gitlab-feature
    
  3. 发布配置

    php artisan vendor:publish --provider=CodingPaws\\GitLabFeature\\FeatureServiceProvider
    
  4. 转到项目功能标志,点击配置
    The configure button is next to the "View user lists" and "New feature flag" buttons

  5. 添加到您的.env配置文件中
    • GITLAB_INSTANCE_ID到配置模态中显示的实例ID
    • GITLAB_API_URL到配置模态中显示的API URL
    • GITLAB_ENV_NAME到您在功能标志部署策略中使用的环境名称。

在PHP中的使用

当您想在PHP中检查功能标志时,例如控制器或模型,您可以使用Feature类。

use CodingPaws\GitLabFeature\Feature;

if (Feature::enabled('colored_shopping_cart')) {
   echo '<div class="shopping-cart__colored" />';
}

if (Feature::disabled('date-format-24h')) {
   $dateFormat = DATE_FORMAT_AMPM;
}

在Blade中的使用

在blade中导入会使视图难以阅读。在视图中,您可以使用提供的辅助方法。

@if(feature_enabled('new_design'))
   <link rel="stylesheet" href="/static/design-2021.css" />
@endif

@unless(feature_disabled('lazyload'))
   <script src="/js/lazyload.min.js" defer async></script>
@endif

功能标志缓存

功能标志使用Laravel Cache系统进行缓存。这提高了您网站的性能并减少了GitLab实例的负载。缓存持续时间可以在您的config/gitlab_feature.php配置文件中使用cache_duration条目进行配置。标准环境变量是GITLAB_CACHE_DURATION。默认情况下,缓存持续时间设置为5分钟。

您还可以手动清除缓存,并使用refresh方法强制重新加载所有功能标志。

use CodingPaws\GitLabFeature\Feature;

Feature::refresh();

自定义用户ID

默认情况下使用Auth::id()根据用户的ID部署功能标志。如果您想根据不同的ID或用户名部署标志,可以注册自定义的用户ID解析器。

use CodingPaws\GitLabFeature\UserIdResolver;

class MyIdResolver extends UserIdResolver
{
  public function resolve(): int|string|null
  {
    return Auth::user()?->name;
  }
}

UserIdResolver::register(new MyIdResolver);

查看所有可用功能标志

在调试问题或进行A/B测试时,查看所有功能标志的状态可能会有所帮助。要获取所有功能标志的列表以及它们是否启用,请使用all方法。

use CodingPaws\GitLabFeature\Feature;

$flags = Feature::all();

echo $flags['cool_feature'] ? 'enabled' : 'disabled';

如何模拟功能标志

可以通过Laravel facade mocking模拟Feature facade来模拟功能标志。

use CodingPaws\GitLabFeature\Feature;

Feature::shouldReceive('enabled')
   ->with('cool_feature')
   ->once()
   ->andReturn(true);

Feature::enabled('cool_feature'); // returns `true`

SSL故障排除

在某些平台或根据您的GitLab实例配置——这不适用于GitLab.com SaaS平台——内置的SSL验证有时会导致问题并且无法正常工作。尽管在Windows开发环境中安装了OpenSSL,但我们仍然遇到了问题。

对于SSL验证失败的情况,您可以通过将gitlab_feature.disable_verification设置为true来禁用它。默认情况下,您可以将GITLAB_DISABLE_VERIFICATION环境变量设置为true