harpya/config-manager

轻量级且安全的配置加载器。

v0.0.3 2020-03-04 05:11 UTC

This package is auto-updated.

Last update: 2024-09-04 18:01:31 UTC


README

此库旨在加载不同类型的配置资源,例如

  • JSON文件
  • YAML文件
  • INI文件
  • .ENV文件

此库还可以加载文件夹内的文件。

一个非常常见的例子是,当您有一个主-JSON文件来定义应用程序中的默认值,并希望与.env文件合并,覆盖一些值时。

如何使用...

$cfg = new ConfigManager();

// Loads the myFile-01.json contents
$cfg->loadJSON(__DIR__.'/myFile-01.json');

// Loads the myFile-02.json contents, overriding the already existent keys
$cfg->loadJSON(__DIR__.'/myFile-02.json');

// Getting the CONFIG-KEY value
$value = $cfg->get('CONFIG-KEY');

// Getting a value that is not defined on those files - return the default
$default = time();
$expireAt = $cfg->get('EXPIRE_AT', $default);


加载JSON格式文件


// Loading a single file
$cfg->loadJSON('path-of-JSON-file');

// Loading all files on a folder
$cfg->loadJsonFolder('folder-of-JSON-files');

加载.env格式文件

// Loading a single file
$cfg->loadEnv('path-of-env-file');

// Loading all files on a folder
$cfg->loadEnvFolder('folder-of-env-files');

加载YAML格式文件

// Loading a single file
$cfg->loadYaml('path-of-yaml-file');

// Loading all files on a folder
$cfg->loadYamlFolder('folder-of-yaml-files');

加载INI格式文件

// Loading a single file
$cfg->loadIni('path-of-ini-file');

// Loading all files on a folder
$cfg->loadIniFolder('folder-of-ini-files');

使用多级键

有时您需要在嵌套结构中获取/设置一些值。您可以使用数组作为键来设置/获取键值,如下面的示例所示

$cfg = new ConfigManager();

$networkConfig = [
    'timeout' => 500,
    'host' => 10.20.30.40
];

// Apply the $networkConfig on $cfg
$cfg->set('network', $networkConfig);

// Overriding programatically the 'timeout' key-value
$cfg->set(['network', 'timeout'],1000);

//...

// If the timeout exists inside of 'network', then use it. Otherwise, return the default (700) value.
$cfg->get(['network', 'timeout'],700);