mefworks/config

Load configurations from multiple sources.

v1.1.1 2020-06-26 16:36 UTC

This package is auto-updated.

Last update: 2024-05-08 20:39:01 UTC


README

Total Downloads Latest Stable Version

mef\Config provides a simple, immutable configuration system.

Example

<?php
$config = (new mef\Config\FileLoader\JsonFileLoader)->loadFile('settings.json');

echo 'The username is: ', $config['database.user'], PHP_EOL;

More complete examples are available in the examples directory.

File Loaders

There are four loaders:

  • mef\Config\FileLoader\IniFileLoader - Loads standard INI files.

  • mef\Config\FileLoader\JsonFileLoader - Loads standard JSON files.

  • mef\Config\FileLoader\PhpFileLoader - Includes a PHP array or callable (that must return an array).

  • mef\Config\FileLoader\YamlFileLoader - Loads standard YAML files (via symfony/yaml).

Each of these loaders returns a mef\Config\ArrayConfig object.

ConfigInterface

The mef\Config\ConfigInterface defines only two methods: get and exists. Both take a string key as the only parameter. If a key does not exist, then a mef\Config\Exception\InvalidKeyException will be thrown.

$config = new ArrayConfig([
  'database' => [
    'user' => 'John'
  ]
]);

if ($config->exists('database') === true) {
  echo $config->get('database')['user'], PHP_EOL;
}

ArrayConfig

The mef\Config\ArrayConfig holds an immutable associative array. As with any configuration object that descends from mef\Config\AbstractConfig, the data can optionally be accessed using dot notation and/or as an array.

echo $config->get('database.user'), PHP_EOL;
echo $config['database']['user'], PHP_EOL;
echo $config['database.user'], PHP_EOL;

CachedConfig

The mef\Config\CachedConfig is a decorator for a ConfigInterface object. It caches the calls to get in a private array. This can be useful so that the common "if exists then get" does not have to resolve the key twice.

MergedConfig

The mef\Config\MergedConfig takes one or more ConfigInterface objects and merges them into a single configuration.

$config = new mef\Config\MergedConfig([$config1, $config2]);

The configurations are passed in the constructor as a single array in ascending priority. i.e., $config2 overrides $config1.

The merging is done such that associative arrays can contain partial overrides. However, indexed based arrays are completely overwritten.