Transform Environment Variable to Backed Enum in Symfony 8

Transform Environment Variable to Backed Enum in Symfony 8

Symfony applications often rely on environment variables to control behavior across different environments. These values are always loaded as strings, but in modern PHP applications we can use backed enums to represent a fixed set of valid options in a type-safe way. This tutorial demonstrates how to transform environment variable to backed enum in Symfony 8 application.

Instead of manually converting a string environment variable into an enum, Symfony provides a built-in solution through the enum environment variable processor. This makes it possible to map an environment variable directly to a PHP backed enum.

Let's say we have environment variable which holds the cache storage. In the .env file define variable as follows:

.env

CACHE_STORE=file

Next, define a backed enum representing the available cache storage options:

src/Enum/CacheStore.php

<?php

namespace App\Enum;

enum CacheStore: string
{
    case FILE = 'file';
    case ARRAY = 'array';
    case REDIS = 'redis';
}

The next step is to instruct Symfony to convert the environment variable into backed enum instance. This is done using the enum environment variable processor.

The processor reads the value of the specified environment variable and attempts to match it with one of the enum backed values. If a matching case is found, the corresponding enum instance is injected. If the value does not match any case, Symfony throws an exception during container compilation, helping detect configuration errors early.

src/Controller/TestController.php

<?php

namespace App\Controller;

use App\Enum\CacheStore;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController
{
    public function __construct(
        #[Autowire(env: 'enum:App\Enum\CacheStore:CACHE_STORE')] private CacheStore $store,
    ) {
    }

    #[Route('/')]
    public function index(): Response
    {
        return new Response($this->store->value);
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.