philiprehberger/php-config-loader

Load configuration from JSON and PHP files with environment variable substitution

Maintainers

Package info

github.com/philiprehberger/php-config-loader

pkg:composer/philiprehberger/php-config-loader

Fund package maintenance!

philiprehberger

Statistics

Installs: 38

Dependents: 0

Suggesters: 0

Stars: 1

Open Issues: 0

v1.2.0 2026-03-28 02:10 UTC

This package is auto-updated.

Last update: 2026-04-22 16:00:24 UTC


README

Tests Latest Version on Packagist Last updated

Load configuration from JSON, PHP, YAML, and TOML files with environment variable substitution.

Requirements

  • PHP 8.2+
  • ext-yaml (optional, required for YAML file support)

Installation

composer require philiprehberger/php-config-loader

Usage

Loading a Single File

use PhilipRehberger\ConfigLoader\ConfigLoader;

// Load a PHP config file
$config = ConfigLoader::load(__DIR__ . '/config/app.php');

// Load a JSON config file
$config = ConfigLoader::load(__DIR__ . '/config/database.json');

// Load a YAML config file (requires ext-yaml)
$config = ConfigLoader::load(__DIR__ . '/config/cache.yaml');

// Load a TOML config file
$config = ConfigLoader::load(__DIR__ . '/config/services.toml');

PHP config file (app.php):

<?php
return [
    'name' => 'MyApp',
    'debug' => true,
    'version' => '1.0.0',
];

JSON config file (database.json):

{
    "host": "localhost",
    "port": 3306,
    "credentials": {
        "user": "admin",
        "pass": "secret"
    }
}

Dot-Notation Access

$config->get('credentials.user');          // 'admin'
$config->get('missing.key', 'default');    // 'default'

Typed Getters

$config->string('name');          // string, default ''
$config->int('port', 3306);       // int, default 0
$config->bool('debug', false);    // bool, default false
$config->float('rate', 1.0);      // float, default 0.0
$config->array('tags', []);       // array, default []

Checking Key Existence

$config->has('credentials.user');  // true
$config->has('nonexistent');       // false

Environment Variable Substitution

Config values containing ${VAR} are resolved from environment variables at load time. Use ${VAR:default} to provide a fallback.

{
    "host": "${DB_HOST:localhost}",
    "api_key": "${API_KEY}"
}
putenv('DB_HOST=production.example.com');
$config = ConfigLoader::load('config.json');

$config->get('host');     // 'production.example.com'
$config->get('api_key');  // '' (env var not set, no default)

Loading a Directory

Load all .php, .json, .yaml, .yml, and .toml files from a directory. Each file's basename (without extension) becomes a top-level key.

// config/
//   app.php      -> keyed as 'app'
//   database.json -> keyed as 'database'

$config = ConfigLoader::loadDirectory(__DIR__ . '/config');

$config->get('app.name');           // from app.php
$config->get('database.host');      // from database.json

Deep Merge

Combine two configurations with deep merging. Values from the second config override the first; nested arrays are merged recursively.

$base = ConfigLoader::load('config/defaults.php');
$local = ConfigLoader::load('config/local.php');

$merged = $base->merge($local);

Flattening Nested Config

Convert nested configuration into a flat associative array with dot-notation keys.

$config = ConfigLoader::load('config/database.php');
// ['database' => ['host' => 'localhost', 'port' => 3306]]

$flat = $config->flatten();
// ['database.host' => 'localhost', 'database.port' => 3306]

// Use a custom separator
$flat = $config->flatten('/');
// ['database/host' => 'localhost', 'database/port' => 3306]

Configuration Validation

Validate config values against a set of rules. Rules are pipe-separated.

$config = ConfigLoader::load('config/database.json');

$violations = $config->validate([
    'host' => 'required|string',
    'port' => 'required|int',
    'debug' => 'bool',
]);

if ($violations !== []) {
    foreach ($violations as $message) {
        echo $message . PHP_EOL;
    }
}

Supported rules: required, string, int, bool, float.

API

Method Return Type Description
ConfigLoader::load(string $path) Config Load a single config file (PHP, JSON, YAML, TOML)
ConfigLoader::loadDirectory(string $dir) Config Load all config files from a directory
Config::get(string $key, mixed $default = null) mixed Get value by dot-notation key
Config::string(string $key, string $default = '') string Get string value
Config::int(string $key, int $default = 0) int Get integer value
Config::bool(string $key, bool $default = false) bool Get boolean value
Config::float(string $key, float $default = 0.0) float Get float value
Config::array(string $key, array $default = []) array Get array value
Config::has(string $key) bool Check if key exists
Config::all() array Get all config data
Config::keys() array Get all top-level configuration keys
Config::merge(Config $other) Config Deep merge with another config
Config::flatten(string $separator = '.') array Flatten nested config to dot-notation key-value pairs
Config::validate(array $rules) array Validate config against rules, returns violation messages

Development

composer install
vendor/bin/phpunit
vendor/bin/pint --test

Support

If you find this project useful:

Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT