mefworks / config
Load configurations from multiple sources.
Requires
- php: >=5.6
Requires (Dev)
- mikey179/vfsstream: ^1.5
- phpunit/phpunit: ^4.4
Suggests
- symfony/yaml: Required for yaml parsing (mef\Config\FileLoader\YamlFileLoader)
This package is auto-updated.
Last update: 2024-12-08 21:51:01 UTC
README
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 (viasymfony/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.