werx/config

在您的应用程序中使用特定环境的配置文件。

1.3 2015-12-13 16:25 UTC

This package is auto-updated.

Last update: 2024-08-29 03:58:01 UTC


README

Build Status Total Downloads Latest Stable Version

在您的应用程序中使用特定环境的配置文件。

功能

  • 多环境支持(例如:local/test/prod)
  • 可扩展配置提供者
    • 默认包含 ArrayProvider 和 JsonProvider
    • 通过实现 \werx\config\Providers\ProviderInterface 创建自己的提供者
  • 通过单次调用加载多个配置文件

基本用法

# Get an instance of the ArrayProvider
$provider = new \werx\Config\Providers\ArrayProvider('/path/to/config/directory');

# Create a Config\Container Instance from this provider.
$config = new \werx\Config\Container($provider);

# Load config/config.php
$config->load('config');

# Get an item.
$item = $config->get('foo');

推荐目录结构

对于默认配置提供者,您需要在项目中的某个位置创建一个目录结构来存储您的配置文件。

推荐结构

config/
    config.php
    another_config.php
    /local/
        config.php
    /test/
        config.php
    /prod/
        config.php

默认配置放在根目录下的 config 目录中。如果您希望在运行不同环境时覆盖默认设置,则还必须为每个环境(local/test/prod)创建子目录。

使用 ArrayProvider

在您的配置目录中创建一个 .php 文件,该文件返回配置值数组。

<?php
return [
	'foo' => 'Foo',
	'bar' => 'Bar'
];

通过将配置目录的路径传递给构造函数来获取 ArrayProvider 类的实例。

$provider = new \werx\Config\Provider\ArrayProvider('/path/to/config/directory');

使用 JsonProvider

在您的配置目录中创建一个 .json 文件,该文件返回配置值数组。

{
    "foo" : "Foo",
    "bar" : "Bar"
}

通过将配置目录的路径传递给构造函数来获取 JsonProvider 类的实例。

$provider = new \werx\Config\Provider\JsonProvider('/path/to/config/directory');

加载配置组

在此示例中,您将加载配置目录中的 config.php 文件中的数组。

$config = new \werx\Config\Container($provider);
$config->load('config');

获取配置值

$item = $config->get('foo');

print $item;
// Foo

获取默认值

如果配置项不存在,$config->get() 将返回 null。您可以通过传递新默认值作为第二个参数来覆盖默认返回值。

$item = $config->get('doesnotexist', false);
var_dump($item);
// false;

加载特定环境的配置组

在此示例中,您将加载 config.phptest/config.php 文件中的数组。来自 test/config.php 的键将合并到来自 config.php 的键中。

$config->setEnvironment('test');
$config->load('config');

注意: 合并策略类似于 PHP 的原生 array_merge 策略,即具有与默认配置相同名称的环境特定配置中的键将替换默认配置中的键。此合并是递归的,因此嵌套键也遵循相同的逻辑。

加载多个配置组

如果您要加载多个配置组,可以多次调用 load(),或者可以将配置组数组传递给它。

$config->load(['config', 'another_config']);

避免配置属性名称冲突

默认情况下,如果配置属性名称在多个配置文件中找到,则配置值将在找到该属性名称的每次配置文件中替换。如果您更喜欢,可以告诉加载器使用配置组名称索引配置容器以防止名称冲突。这可以通过将 true 作为 load() 的第二个参数传递来实现。

$config->load(['config', 'email'], true);

然后,通过调用与加载的配置文件同名的“魔法”方法来检索索引的属性名称。

// Get the value for the 'host' property from the 'email' configuration group.
$item = $config->email('host', 'smtp.mailgun.org');

get() 方法一样,上面的第二个参数是不存在的配置项的默认值。

或者,您可以通过不传递任何参数来返回 'email' 配置组中的所有项作为数组。

$items = $config->email();

安装

此软件包可通过 Composer 作为 werx/config 安装和自动加载。如果您不熟悉 PHP 的 Composer 依赖关系管理器,您应该先阅读此内容

$ composer require werx/config --prefer-dist

贡献

单元测试

$ vendor/bin/phpunit

编码标准

这个库使用 PHP_CodeSniffer 来确保遵循编码标准。

我采用了 PHP FIG PSR-2 编码标准,除了缩进使用的制表符与空格规则。PSR-2 要求使用 4 个空格。我使用制表符。不接受讨论。

为了支持使用制表符缩进,我定义了一个自定义的 PSR-2 规则集,该规则集扩展了 PHP_CodeSniffer 使用的标准 PSR-2 规则集。您可以在本项目的根目录中找到此规则集,名为 PSR2Tabs.xml。

从本项目的根目录执行 codesniffer 命令以运行使用这些自定义规则的 sniffer。

$ ./codesniffer