matiasnamendola/slimpower-config

Config 是一个支持 PHP、INI、XML、JSON 和 YML 文件配置加载器。

v0.0.1-alpha 2016-12-07 02:33 UTC

This package is not auto-updated.

Last update: 2024-09-28 21:21:14 UTC


README

Latest version Total Downloads

Latest Stable Version Latest Unstable Version Total Downloads Monthly Downloads Daily Downloads composer.lock available

Config 是一个支持 PHP、INI、XML、JSON 和 YML 文件配置加载器。

安装

在终端中

composer require matiasnamendola/slimpower-config

或者您可以将此添加到您的 composer.json 中

{
    "require": {
        "matiasnamendola/slimpower-config": "dev-master"
    }
}

要求

Config 需要 PHP 5.3+,并建议使用 Symfony Yaml 组件

Config 设计得非常简单直观,您可以用它来加载、获取和设置。

加载文件

可以通过工厂方法 load() 或直接实例化来创建 Config 对象。

<?php

use SlimPower\Config\Config;

// Load a single file
$conf = Config::load('config.json');
$conf = new Config('config.json');

// Load values from multiple files
$conf = new Config(array('config.json', 'config.xml'));

// Load all supported files in a directory
$conf = new Config(__DIR__ . '/config');

// Load values from optional files
$conf = new Config(array('config.dist.json', '?config.json'));

根据文件扩展名解析和加载文件。注意,当加载多个文件时,具有 重复键的条目将采用最后加载的文件中的值

当加载目录时,路径将 glob 化,并按名称字母顺序加载文件。

获取值

可以通过三种方式获取值。一种是通过使用 get() 方法

// Get value using key
$debug = $conf->get('debug');

// Get value using nested key
$secret = $conf->get('security.secret');

// Get a value with a fallback
$ttl = $conf->get('app.timeout', 3000);

第二种方法,就像使用数组一样使用它

// Get value using a simple key
$debug = $conf['debug'];

// Get value using a nested key
$secret = $conf['security.secret'];

// Get nested value like you would from a nested array
$secret = $conf['security']['secret'];

第三种方法,是使用 all() 方法

// Get all values
$data = $conf->all();

设置值

尽管 Config 通过 set() 或数组语法支持设置值,但通过这种方式进行的任何更改 都不会反映回源文件。按照设计,如果您需要更改配置文件,您必须手动进行。

$conf = Config::load('config.json');

// Sample value from our config file
assert($conf['secret'] == '123');

// Update config value to something else
$conf['secret'] = '456';

// Reload the file
$conf = Config::load('config.json');

// Same value as before
assert($conf['secret'] == '123');

// This will fail
assert($conf['secret'] == '456');

使用默认值

有时在您自己的项目中,您可能希望使用 Config 来存储应用程序设置,而不需要文件 I/O。您可以通过扩展 AbstractConfig 类并填充 getDefaults() 方法来实现这一点

<?php

namespace ...;

use SlimPower\Config\AbstractConfig;

class MyConfig extends AbstractConfig
{
    protected function getDefaults()
    {
        return array(
            'host' => 'localhost',
            'port'    => 80,
            'servers' => array(
                'host1',
                'host2',
                'host3'
            ),
            'application' => array(
                'name'   => 'configuration',
                'secret' => 's3cr3t'
            )
        );
    }
}

致谢

许可证

MIT 许可证 (MIT)。有关更多信息,请参阅 许可证文件