climbx/config

管理框架配置文件的工具。实现了PSR-11规范。

1.0.4 2021-07-06 00:00 UTC

This package is auto-updated.

Last update: 2024-09-29 06:20:19 UTC


README

框架配置文件管理器。实现了PSR-11规范。

配置文件格式

此组件接受Yaml和Json文件格式。

完整示例

使用JsonLoader

// myConfig.json

{
  "FOO": "BAR"
}
// PHP Code

use Climbx\Bag\Bag;
use Climbx\Config\Loader\JsonLoader;
use Climbx\Filesystem\FileHelper;
use Climbx\Config\Parser\EnvVarParser;
use Climbx\Config\Reader\Reader;
use Climbx\Config\ConfigContainer;

// Bag with array of .env data

// JsonLoader
$jsonLoader = new JsonLoader(__DIR__ . 'config/', new FileHelper());

// Config files Reader
$env = new Bag(['FOO' => 'BAR']); // loaded from .env file
$reader = new Reader($jsonLoader, new EnvVarParser($env));

// Container
$container = new ConfigContainer($reader);

/*
 * get() method
 * 
 * If the config file exists it will be returned
 * 
 * If not, a NotFoundException is thrown.
 * 
 * If the config file is not valid, a ConfigurationParserException
 * is thrown
 * 
 * If a referenced .env var is missing in .env file,
 * a EnvParameterNotFoundException is thrown.
 */
$config = $container->get('myConfigId');

/*
 * has() method.
 * 
 * This method returns true if the config exists and is readable,
 * and false otherwise.
 */
$config = $container->has('myConfigId');

环境变量解析器

可以在配置变量中添加对.env变量引用。使用魔法表达式$env(MY_ENV_VAR)完成。如果引用存在于.env中,它将被其值替换。如果不存在,将抛出EnvParameterNotFoundException异常。

# .env file

FOO=BAR
# config.yaml

BAZ: $env(FOO)
// PHP Code

$container = new ConfigContainer($reader);

$config = $container->get('config');
echo $config->get('BAZ'); // Will print: BAR