[go: up one dir, main page]

DEV Community

Cover image for Basic Feature Flags in Laravel
Bennett
Bennett

Posted on

Basic Feature Flags in Laravel

Feature Flags (or toggles) are used to conveniently enable or disable features in an application. Feature Flags make it easier to test, manage, and roll out new features.

The following is a bare-bones implementation using a service provider approach.

This approach consists of:

  • An enum
  • A service provider
  • A global helper

The Enum

We will use an enum to represent each feature we want to manage.

In App\Enums create the enum:

enum Feature
{
    case EnableAddToCart;
    case EnableCheckout;
    case EnableReviews;
    // ... 
}
Enter fullscreen mode Exit fullscreen mode

The Service Provider

The provider will be the sole source of truth in determining which features are enabled and allows for a central location for feature management. To disable a feature, simply comment it out.

Generate a new service provider using php artisan make:provider FeatureProvider.

Be sure to register the service provider according to your version of Laravel.

Add each Feature enum case to this provider.

/**
* Register services.
*/
public function register(): void
{
    $this->app->singleton('features', [
        Feature::EnableAddToCart,
        Feature::EnableCheckout,
        // Feature::EnableReviews
    ]);
}
Enter fullscreen mode Exit fullscreen mode

The Global Helper

Registering global helper functions in Laravel is a breeze!

In the App directory create helpers.php:

<?php

use App\Enums\Feature;

/**
 * Check if a feature is enabled
 */
if(! function_exists('featureEnabled')) {

    function featureEnabled(Feature $feature): bool
    {
        return in_array($feature, app('features'));
    }
}
Enter fullscreen mode Exit fullscreen mode

Next, add this file to the autoload config in composer.json:

"autoload": {
    "psr-4": {
        "App\\": "app/",
        "Database\\Factories\\": "database/factories/",
        "Database\\Seeders\\": "database/seeders/"
    },
    "files": [
        "app/helpers.php"
    ]
},
Enter fullscreen mode Exit fullscreen mode

Usage

Now you can perform feature checks anywhere in your app with the helper function:

if(featureEnabled(Feature::EnableCheckout)){
    // ...
}
Enter fullscreen mode Exit fullscreen mode

Taking it a Step Further

This lightweight implementation can be easily modified to allow for conditionally enabling features in the provider.

$features = [
    Feature::EnableAddToCart => env('ENABLE_CART'),
    Feature::EnableCheckout => $this->authorizeCheckout(),
    Feature::EnableReviews => Cache::get('reviewed')
];

$this->app->singleton('features', fn() => array_keys(array_filter($features));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)