Feature flags in your Symfony project 🌱

mguinea

Marc Guinea

Posted on August 6, 2021

Feature flags in your Symfony project 🌱

Feature flag, or also known as Feature switch, is a functionality that allows to your app to enable or disable some parts on runtime depending on your needs.

Why?

There are many reasons to implement feature flags in your project:

  1. An specific feature must be available for a single customer at first.
  2. You have to deploy it but it's not finished yet.
  3. Feature is production ready but there is an specific date to be available to public API...

How?

First of all, let's create an interface to abstract the implementation:

interface FeatureChecker
{
    public function isEnabled(string $feature): bool;
}
Enter fullscreen mode Exit fullscreen mode

At this point, we can implement it in several ways. Let's see the easiest one: In Memory implementation

class InMemoryFeatureChecker implements FeatureChecker
{
    private array $features;

    public function __construct(array $features = [])
    {
        $this->features = $features;
    }

    public function isEnabled(string $feature): bool
    {
        return $this->features[$feature] ?? false;
    }
}
Enter fullscreen mode Exit fullscreen mode

If using Symfony, we can use Service Container to set that feature flags in a yml file when injecting the FeatureChecker in our code:

First, we should register our service:

services:
    InMemoryFeatureChecker:
        public: true
        arguments:
            - '%features%'
Enter fullscreen mode Exit fullscreen mode

Then, using Service Container parameters we set the argument:

parameters:
    features:
        {
            foo: false,
            bar: true
        }
Enter fullscreen mode Exit fullscreen mode

Example

Let's imagine following situation: you have an endpoint that shouldn't be active yet, but it is already implemented:

class SomeController
{
    private FeatureChecker $featureChecker;

    public function __construct(FeatureChecker $featureChecker) 
    {
        $this->featureChecker = $featureChecker;
    }

    public function __invoke(Request $request): JsonResponse
    {
        if (false === $this->featureChecker->isEnabled('foo')) {
            // throw exception to exit endpoint
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Having the interface, you can implement it as better fits to your requirements (from yml files, from redis, mysql...).

Using feature flags, you have a tool to enable / disable easily features of your application.

Our approach has been really basic, but can be extended containing more info about user, quota usage, timestamp to be available from specific moment...

💖 💪 🙅 🚩
mguinea
Marc Guinea

Posted on August 6, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related