grotthecheat/yaml-config

YAML 配置文件管理库。

v1.0.5-stable 2023-06-09 10:34 UTC

This package is auto-updated.

Last update: 2024-09-09 13:22:13 UTC


README

grotthecheat/yaml-config 包是一个轻量级的 YAML 配置文件管理库,使用点符号键来方便地访问嵌套值。

文件加载

YamlConfig 可以直接实例化,将要加载的文件路径传递给构造函数。

use GrotTheCheat\YamlConfig;
use GrotTheCheat\YamlConfig\Exceptions;

try {
    $config = new YamlConfig\YamlConfig('config_file_path');
} catch (Exceptions\FileNotFoundException $ex) {
    echo $ex->getMessage();
}

或者,YamlConfig 实现了一个自包含的工厂函数 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);

需要注意的是,直接实例化一个实例将在请求的文件不存在时抛出错误,而工厂方法将简单地返回 false。

示例 YAML 配置 - 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

示例

// 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']);