helhum/config-loader

支持上下文和环境的一般配置加载器。

v0.12.5 2022-02-21 15:32 UTC

README

这是一个类,它可以帮助您合并基本配置与不同上下文和环境的配置。

使用composer安装它:composer require helhum/config-loader

基本用法

$context = 'production';
$confDir = '/path/to/conf';
$configReaderFactory = new \Helhum\ConfigLoader\ConfigurationReaderFactory($confDir);
$configLoader = new \Helhum\ConfigLoader\ConfigurationLoader(
    [
        $configReaderFactory->createReader($confDir . '/default.php'),
        $configReaderFactory->createReader($confDir . '/' . $context . '.php'),
        $configReaderFactory->createReader('PREFIX', ['type' => 'env']),
        $configReaderFactory->createReader($confDir . '/override.php'),
    ]
);
$config = $configLoader->load();

基本用法缓存

$context = 'production';
$confDir = '/path/to/conf';
$cacheDir = '/path/to/cache';
$cacheIdentifier = md5($context . filemtime('/path/to/.env'));
$configReaderFactory = new \Helhum\ConfigLoader\ConfigurationReaderFactory($confDir);
$configLoader = new \Helhum\ConfigLoader\CachedConfigurationLoader(
    $cacheDir,
    $cacheIdentifier,
    function() use ($confDir, $context, $configReaderFactory) {
        return new \Helhum\ConfigLoader\ConfigurationLoader(
            [
                $configReaderFactory->createReader($confDir . '/default.php'),
                $configReaderFactory->createReader($confDir . '/' . $context . '.php'),
                $configReaderFactory->createReader('PREFIX', ['type' => 'env']),
                $configReaderFactory->createReader($confDir . '/override.php'),
            ]
        );
    }
);
$config = $configLoader->load();

使用处理器

可以向配置加载器添加一个或多个处理器。

$context = 'production';
$confDir = '/path/to/conf';
$configReaderFactory = new \Helhum\ConfigLoader\ConfigurationReaderFactory($confDir);
$configLoader = new \Helhum\ConfigLoader\ConfigurationLoader(
    [
        $configReaderFactory->createReader($confDir . '/config.php'),
    ],
    [
        new \Helhum\ConfigLoader\Processor\PlaceholderValue(),
    ]
);
$config = $configLoader->load();

高级用法

而不是硬编码要包含哪些配置源,可以在一个配置文件内部包含多个源。

$context = 'production';
$confDir = '/path/to/conf';
$configReaderFactory = new \Helhum\ConfigLoader\ConfigurationReaderFactory($confDir);
$configLoader = new \Helhum\ConfigLoader\ConfigurationLoader(
    [
        $configReaderFactory->createRootReader($confDir . '/config.yaml'),
    ]
);
$config = $configLoader->load();

配置文件可以包含一个import部分

imports:
    - { resource: 'config.*.yml', type: glob }
    - { resource: 'env.yml' }

反馈

欢迎任何反馈。请提交错误报告、功能请求、创建pull请求,或通过Twitter发给我“谢谢”,或者传播这个消息。

谢谢!