krak/config

轻量级配置注册表

v0.1.0 2017-05-01 04:49 UTC

This package is auto-updated.

Last update: 2024-09-18 17:37:45 UTC


README

配置库提供了一个简单的接口来添加配置值。所有配置文件都只有在被调用时才会懒加载,这提供了一种干净且高效的管理配置的方法。

安装

使用 composer 在 krak/config 下安装

用法

所有配置都通过 ConfigStore 管理。 Config\store 提供了一个默认实例,该实例将懒加载文件/数据并将结果缓存起来,以防止多次调用文件系统。

添加配置项

在同一个键下添加多个条目将在检索时合并数据。最后添加的条目将覆盖之前的条目。

<?php

$config = Krak\Config\store();
// add array data
$config->add('a', [
    'from_array' => true,
    'b' => ['c' => 1]
]);
$config->add('a', function() {
    return ['from_closure' => true],
});
// You can add, php, ini, json, or yml files, but you must provide the full path
$config->add('a', __DIR__ . '/path/a.php');

// or you can use this helper for files
$config->addFiles(__DIR__ . '/path', [
    'a.php',
]);
$config->addPhpFiles(__DIR__ . '/path', ['a']); // this is the exact same as above

PHP 配置文件必须返回一个数组,如下所示

<?php

return [
    'from_php_file' => true
];

注意:对于 YAML 文件,您必须安装 Symfony YAML 组件 (symfony/yaml)。

获取配置项

<?php

var_dump($config->get('a'));

// or retrieve nested items
$config->get('a.b.c');

这将显示类似以下的内容

array(4) {
  ["from_array"]=>
  bool(true)
  ["from_closure"]=>
  bool(true)
  ["from_php_file"]=>
  bool(true)
}