Feature Toggle Utility

The FeatureToggleUtil in the LaraUtilX package provides functionality for enabling or disabling features based on configuration settings, with support for per-user or per-environment overrides.

Methods

  1. isEnabled(string $feature): bool: Checks if a feature is enabled.

Usage

  1. Check Feature Status: To check if a feature is enabled, use the isEnabled method:

    use LaraUtilX\Utilities\FeatureToggleUtil;
    
    if (FeatureToggleUtil::isEnabled('my_feature')) {
       // Feature is enabled
    } else {
       // Feature is disabled
    }
  2. Configuration: Define feature toggles in config/feature-toggles.php. A feature is either a plain boolean or an array carrying overrides. It cannot be both, and a key can only appear once.

    // config/feature-toggles.php
    return [
        // Simple on/off
        'my_feature' => true,
    
        // With overrides
        'new_billing' => [
            'enabled'     => false,
            'user'        => [1 => false, 42 => true],
            'environment' => ['local' => true, 'production' => false],
        ],
    ];
  3. Override precedence: The most specific match wins. The authenticated user's entry is checked first, then the current environment, and finally enabled. A feature with no matching entry is disabled.

Changed in v1.5.4. Declaring a feature as an array previously threw, because the array was returned from a method typed bool. Overrides also had to be written as 'my_feature.user.1', which collided with the boolean form of the same key.

Result

The utility returns a boolean value indicating whether the feature is enabled or disabled. It also supports per-user and per-environment overrides, providing flexibility in feature management.

Defaults ship with the package and are merged by the service provider, so isEnabled() works before you publish anything. Earlier releases copied the config file into your application's config/ directory on first call, which failed on read-only deploys and was ignored once config:cache had run.

Publish Config

You can publish the feature-toggles config file through the below command:

php artisan vendor:publish --tag=lara-util-x-feature-toggles


This utility simplifies feature toggling, allowing for easy control over feature availability based on configuration settings.