grotthecheat / yaml-config
YAML configuration file management library.
v1.0.5-stable
2023-06-09 10:34 UTC
Requires
- php: >=7.2.0
- symfony/yaml: ^6.2
Requires (Dev)
- phpunit/phpunit: ^10.1
This package is auto-updated.
Last update: 2024-04-09 12:19:00 UTC
README
The grotthecheat/yaml-config
package is a lightweight YAML configuration
file management library, employing a dot-notation of keys" for easily accessing
nested values.
Loading Files
YamlConfig can either be directly instantiated passing the path of the file to be loaded into the constructor.
use GrotTheCheat\YamlConfig;
use GrotTheCheat\YamlConfig\Exceptions;
try {
$config = new YamlConfig\YamlConfig('config_file_path');
} catch (Exceptions\FileNotFoundException $ex) {
echo $ex->getMessage();
}
Alternatively, YamlConfig implements a self-contained factory function
load()
.
use GrotTheCheat\YamlConfig;
// load a YAML config file.
$config = YamlConfig\YamlConfig::load('config_file_path.yaml');
// or
// create a new YAML config file, if the specified file does not exist.
$config = YamlConfig\YamlConfig::load('config_file_path.yaml', true);
It's worth noting that directly instantiating an instance will throw an error if the requested file doesn't exist, while the factory method will simply return false.
Sample YAML Config - test.yaml
setting1: value1
setting2: value2
setting3:
sub-setting1: value3
sub-setting2: value4
sub-setting3:
sub-setting4: value 5
setting4:
- value 6
- value 7
- value 8
Example
// using the test.yaml above
$config = YamlConfig::load('test.yaml');
echo $config->get('setting1'); // returns 'value1'
// using a dot-notation sub-settings can be accessed directly
echo $config->get('setting3.sub-setting1'); //returns 'value3'
// there is currently no restriction on the level to which sub-item can be added
echo $config->get('setting3.sub-setting3.sub-setting4'); //returns 'value5'
// lists are returned as arrays
echo $config->get('setting4'); // returns ['value6', 'value7', 'value8']
$config->set('setting1', 'new-value-1');
// dot-notation can be used to set nested values.
$config->set('setting3.sub-setting2', 'new-value-4');
// array can be stored and are saved as YAML lists.
$config->set('setting5', ['value9','value10','value11']);