How to use feature flags in a PHP application
Tags: featureflag, php, configcat, featurerelease
Published: 2022-09-23 12:06:18

It has become very rare to develop software that does not require regular updates and patches. In fact, it's now the norm with the rise of agile software development. As a result, there are so many new updates to manage across our code making feature rollouts tedious and complex. Hence, turning towards a good feature flagging solution always saves the day.

## What are feature flags?

Feature flags are boolean values assigned to particular features/components to enable or disable them. They are normally used within a larger feature flagging system and are commonly referred to as feature switches or feature toggles. You can use them as part of conditional statements in your code to control which features users are allowed to see or interact with. It is possible to flag features in many of the programming languages we already know and use. 

Using them in a PHP application requires a few prerequisites, so let's start by looking at them:

### Prerequisites

- A code editor (eg. Visual Studio Code)
- Composer version 2 - a tool for managing dependencies in PHP
- Node version 16+
- NPM version 8+ - a package manager for setting up and building the frontend
- PHP version 7.4
- Basic PHP knowledge

## Using Feature flagging in PHP

To simplify the process, we can use a hosted feature flag service like [ConfigCat](https://configcat.com/) to create and manage our feature flag. As a bonus tip, if you decide not to deploy features to your entire user base, there are settings in the dashboard you can access after [signing up](https://app.configcat.com/signup) that you can configure to only target specific user segments based on characteristics. For example, you might want to enable certain features for users who are between 25 and 35 years of age living in France.

## How to use the sample app

You can follow along by using this [sample PHP app](https://github.com/configcat-labs/feature-flags-in-php-sample) which uses the Laravel framework and Vue.js on the frontend. It contains a book list component that is shown to users upon receiving an array of books returned from the backend. In this way, we can control this feature from our PHP code with the help of feature flagging.

Here are the steps for building and running it:

**1.** Clone the [code repository](https://github.com/configcat-labs/feature-flags-in-php-sample).

**2.** Run the following command to install PHP's dependencies:

```sh
composer install
```

**3.** Compile the frontend with NPM using the following command:

```sh
npm run dev
```

**4.** Start the PHP server with this command:

```sh
php artisan serve
```

You should now be able to see the app by visiting [http://127.0.0.1:8000/](http://127.0.0.1:8000/).


![Snapshot of sample app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4mo87rfkmlco75vgqdov.png)

 Notice the list of books is displayed? Let's create and configure a feature flag so that this component can be enabled or disabled.

## Creating a feature flag

**1.** Sign up for a [free ConfigCat account](https://app.configcat.com/signup).

**2.** Create a feature flag with the following details:

| Field      | Value |
| ----------- | ----------- |
| **name**     | canShowBooks |
| **key**   | canshowbooks |


![Snapshot of creating a feature flag](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/onfrjtvtpms9rvecdsg3.png)

Click the switcher on the right to enable this feature:

![Snapshot of turning on the feature flag](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fyktwue978e69k4bko5h.png)

Having created and enabled our feature flag, it's time to add ConfigCat to our app so we can track its status.

## Integrating with ConfigCat

> It is strongly recommended to use the ConfigCat Client as a [Singleton](https://en.wikipedia.org/wiki/Singleton_pattern) object in production.

**1.** Install the ConfigCat client SDK with composer:

```sh
composer require configcat/configcat-client
```

**2.** Import the **autoload.php** file which includes the SDK we installed above:

```php
require '../vendor/autoload.php';
```

**3.** I've created a simple book controller API that returns a list of books. Here's the code with included comments:

```php
class BookController extends Controller
{
    // Rest of the code omitted for clarity
    
    public function index()
    {
        // Create the ConfigCat client with your SDK key
        $client = new \ConfigCat\ConfigCatClient("YOUR_SDK_KEY");

        // Create a variable to store the current state of the feature flag
        $canshowbooks = $client->getValue("canshowbooks", false);

        $books = Book::all();

        // Add a conditional block...
        if ($canshowbooks) {
            // Return the list of books if the feature flag is turned on
            return response()->json($books);
        } else {
            // Return an empty array otherwise
            return response()->json([]);
        }
    }

    // Rest of the code omitted for clarity
}
```

## Let's test it out

**1.** Head over to the ConfigCat dashboard and **turn off** the feature flag:


![Snapshot of turning off the feature flag](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ylt4yczxipar8mj8uar.png)

**2.** Reload the page, and you should no longer see the list of books as shown below:


![Snapshot of sample app - feature flag turned off](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5m7prddc2ikh2qljhj3k.png)

## Final words

In summary, integrating feature flags into your PHP app is easy and doesn't require much effort. The use of feature flagging is ideal for development workflows with a steady release of new features.

[ConfigCat's documentation](https://configcat.com/docs/getting-started/) is well explained, making it super simple for you or your team to get up and running fast with its 10-minute trainable feature flag management interface.

ConfigCat also supports other frameworks and languages besides PHP. The full list of supported SDKs can be found [here](https://configcat.com/docs/sdk-reference/overview).

Stay tuned and in the loop with ConfigCat on [Twitter](https://twitter.com/configcat), [Facebook](https://www.facebook.com/configcat), [LinkedIn](https://www.linkedin.com/company/configcat/), and [GitHub](https://github.com/configcat).