jan-di / config
Library to load, validate and cache configuration from environment variables and .env files
Requires
- php: >=7.4
Requires (Dev)
- dg/bypass-finals: ^1.3
- friendsofphp/php-cs-fixer: ^2.17
- josegonzalez/dotenv: ^3.2
- mikey179/vfsstream: ^1.6
- phpunit/phpunit: ^9.5
- psalm/plugin-phpunit: ^0.15.0
- symfony/dotenv: ^5.2
- vimeo/psalm: ^4.3
- vlucas/phpdotenv: ^5.2
Suggests
- josegonzalez/dotenv: Optional for loading .env files
- symfony/dotenv: Optional for loading .env files
- vlucas/phpdotenv: Optional for loading .env files
README
Library to load, validate and cache configuration from environment variables and .env files
Install
Install via composer:
composer require jan-di/config
Usage
Basic Usage
When creating the Config Builder, specify all definitions for the config values. You can use certain type specific constraints to validate the values later. By default, values are read from the environment variables. Optionally you can enable a Dotenv Adapter to add variables from a .env file to the environment before building the config.
use Dotenv\Dotenv; use Jandi\Config\ConfigBuilder; use Jandi\Config\Dotenv\VlucasDotenvAdapter; use Jandi\Config\Entry\StringEntry; // define all config entries via a fluent API: $configBuilder = new ConfigBuilder([ (new StringEntry('APP_ENV', 'development')), (new StringEntry('APP_TOKEN'))->setMinLength(20) ]); // optional: Add a Dotenv loader to load .env files in environment before building config $dotenv = Dotenv::createImmutable(__DIR__, ''); $configBuilder->enableDotEnv(new VlucasDotenvAdapter($dotenv)); // build config array from environment variables // The values will be fetched validated against the rules from the entries. $config = $configBuilder->build();
Configuration Cache
To improve performance and prevent that .env files are parsed on every request, the config values should be cached. This will create a compiled PHP file that holds all fetched values. This file should be cached by Opcache to optimize further.
use Dotenv\Dotenv; use Jandi\Config\ConfigBuilder; use Jandi\Config\Dotenv\VlucasDotenvAdapter; use Jandi\Config\Entry\StringEntry; // build config, see above $configBuilder = new ConfigBuilder([ (new StringEntry('APP_ENV'))->setDefaultValue('development'), (new StringEntry('APP_TOKEN'))->setMinLength(20) ]); $configBuilder ->enableCaching('/path/to/cache/file') // Activate caching ->enableDotEnv(new VlucasDotenvAdapter(Dotenv::createImmutable(__DIR__, '.env'))); // Since caching is enabled, the builder will check if the cache file exists. // if the cache file exists, no values are read from .env or the real environment. $config = $configBuilder->build(); // The cache file is not created automatically. Instead you have to provide a condition, // when the cache has to be written. Often this is related to the values inside the config. if (!$config->isCached() && $config->getValue('APP_ENV') === 'production') { $configBuilder->dumpCache($config); }
Validating values and default values
Each Entrytype has its own set of validating rules that can be set using a fluent API. A specified value must comply to all rules, otherwise the config is not built. Note that the default value is also validated against the ruleset to ensure that its also a valid value. Every entry that does not have a default value, must be specified. Otherwise the container won't get built successfully.
(new StringEntry('STRING', 'value1')) ->setMinLength(5) ->setMaxLength(10) ->setAllowedValues(['value1','value2']) ->setRegexPattern('/value.*/') (new BoolEntry('BOOL', 'true')); (new IntEntry('INT', '3')) ->setLowerLimit(0) ->setUpperLimit(8); (new FloatEntry('FLOAT', '5.5')) ->setLowerLimit(3.4) ->setUpperLimit(7.8);
Catch Errors
The container builder is designed to stop if atleast one variable is missing or has an invalid value. This assures that a successfully built config always have all needed values. The BuildException has a few methods to show summaries of all missing/invalid values in different formats.
try { $builder->build(); } catch(BuildExceptionTest $e) { echo $e->getTextSummary(); exit; } // There where 2 error/s while building configuration: // // APP_ENV [string] Value is invalid: not allowed. Allowed values: abce. // APP_TOKEN [string] Variable is missing and has no default value.
Export to Array
You can export the values/default values to a simple array to process it further.
$config = $configBuilder->build(); $values = $config->exportValues(); $defaultValues = $config->exportDefaultValues(); // returns something like: ['APP_ENV' => 'development']
Supported DotEnv adapters
Currently, the following Dotenv Libraries are supported out of the box:
Alternatively you can provide you own by implementing AdapterInterface