m1/vars

Vars 是一个简单易用且易于扩展的配置加载器,内置了对 ini、json、PHP、toml、XML 和 yaml/yml 文件类型的支持。它还提供了对 Silex 的内置支持以及更多即将到来的框架。

1.1.2 2016-05-18 12:35 UTC

This package is auto-updated.

Last update: 2024-09-21 19:36:24 UTC


README

Author Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads

Vars 是一个简单易用、轻量级且易于扩展的配置加载器,内置了对 ENV、INI、JSON、PHP、Toml、XML 和 YAML 文件类型的支持。它还提供了对 Silex 的内置支持以及更多即将到来的框架(如 Symfony、Laravel 等)。

为什么选择 Vars?

有时您被迫使用不同的配置文件格式,Vars 的一个目标就是通过支持最常见的配置格式来简化这一过程,这样您就不必切换库来处理不同的格式。

另一个目标是支持不同的框架,因此您在处理不同框架时也不必切换库。目前仅支持使用服务提供者进行 Silex,Laravel 和 Symfony 的支持即将推出。

通过简单的 API 和直观的加载选项,Vars 尝试使配置加载和提供尽可能简单。

要求

Vars 需要 PHP 版本 5.3+

如果您想使用 YAML,则需要 symfony/yaml 库,同样地,您还需要 yosymfony/toml 来使用 Toml 文件,以及 m1/env 来使用 Env 文件。

安装

通过 Composer

$ composer require m1/vars

使用

基础

// load single file
$vars = new Vars(__DIR__.'/config/config.yml');

// load from dir
$vars = new Vars(__DIR__.'/config');

// load from array
$vars = new Vars(array(
    __DIR__.'/config/config.yml',
    __DIR__.'/config/sub',
));

访问配置

这可以通过多种方式完成,您可以将 $vars 变量视为一个普通数组,或者以面向对象的方式使用它

// All return the same thing
$vars->get('db.password')
$vars['db.password'];
$vars['db']['password']

您也可以以同样的方式设置值

// All do the same thing
$vars->set('db.password', 'test')
$vars['db.password'] = 'test';
$vars['db']['password'] = 'test';

您还可以从 getenv() 获取变量

// All do the same thing
$vars->toEnv();
getenv('db.password');

有关更多信息,请参阅环境变量部分

导入

导入文件

您可以将配置轻松地相对或绝对地导入到其他配置中,这些导入方式取决于配置文件类型,请检查 /tests/mocks/ 目录以获取示例

# example_1.yml
test_key_1: test_value_1
imports: example_2.yml

# example_2.yml
test_key_2: test_value_2

将返回

[
    "test_key_1" => "test_value_1",
    "test_key_2" => "test_value_2"
]

默认情况下,导入是相对于键导入的,例如

test_key_1:
    imports: example_2.yml

将返回

[
    "test_key_1" => [
        "test_key_2" => "test_value_2"
    ]
]

但是您可以通过多种方式更改此设置

# example 1
test_key_1:
    imports: 
    - {resource: example.yml, relative: false}

# example 2
test_key_2:
    imports:
        resource: example.yml
        relative: false

如果您导入多个文件并希望将所有文件的相对性设置为相对的,您可以执行以下操作

test_key_1:
    imports: 
        relative: false
        resource:
            - example_2.yml
            - example_3.yml

上述所有操作都将使 example_2.ymlexample_3.yml 变量相对于配置文件成为绝对的

[
    "test_key_1" => []
    "test_key_2" => "test_value_2" // from example_2.yml
    "test_key_3" => "test_value_3" // from example_3.yml
]

导入目录

您还可以使用上述所有语法导入目录

test_key_1:
    imports: sub/

默认情况下,导入目录不是递归的,并且不会在文件夹内搜索文件夹,您可以通过添加递归切换来更改此设置

test_key_1:
    imports:
        resource: sub/
        recursive: true

或者通过添加递归标志

test_key_1:
    imports:
        resource: sub/*

与加载文件一样,您可以通过一个递归切换来批量导入目录

test_key_1:
    imports:
        recursive: false
        resource:
            - sub/
            - sub1/

目录的导入依赖于加载器和加载器支持的扩展。有关更多详细信息,请参阅加载器部分。

标志选项

导入时可以使用各种标志。

if else 标志 ?: 使得如果第一个文件存在,则使用该文件 -- 否则使用其他定义的文件,例如

imports: "example_1.yml ?: example_2.yml"

注意:您需要用引号括起字符串,才能使 if else 标志生效

抑制异常标志 @ -- 抑制文件未找到异常。例如

imports: @file_does_not_exist.yml

递归标志使得在目录内搜索文件。例如

imports:
    resource: sub/*

您还可以组合上述标志,因此如果 else 文件选项不存在,则不会引发异常,例如

imports: "example_1.yml ?: @example_2.yml"

资源

您可以获取单个文件或资源

// All return the same thing
$vars->getResource('example_2.yml')->get('test_key_2');
$vars->getResource('example_2.yml')['test_key_2'];

选项

对于 Vars 有各种选项

$vars = new Vars(__DIR__.'/config/config.yml', [
    // this will affect how you getResource() and will  default to the path
    // of the first resource you initiate
    'path' => __DIR__.'/config',

    // to cache or not -- defaults to true
    'cache' => true,

    // where the cache is stored -- If not set will default to the base path
    'cache_path' => __DIR__.'/config/',

    // How long the cache lasts for -- Defaults to 300 seconds (5 minutes)
    'cache_expire' => 300,

    // Replacement variables -- see variables section for more detail
    'replacements' => [
        'foo' => 'bar',
        'foobar' => 'barfoo'
    ],
    
    // Merge globals -- see globals section for more detail
    'merge_globals' => true,

    // The file loaders to load the configs -- see loader section for more detail
    'loaders' => [
        'default'
    ]
]);

基本路径

path 是如何计算 $filename$vars->getResource($filename) 中的。例如

如果您将 path 设置为 __DIR__.'/config' 并且您导入了 __DIR__.'/app/test_1.yml'

# example_1.yml
imports: example_2.yml

那么 example_1.ymlexample_2.yml$filename 分别是 ../app/test_1.yml../app/test_1.yml

如果没有设置 path,则第一个文件资源路径将被用作 path,例如

// example 1
$vars = new Vars(__DIR__.'/config/config.yml');

// example 2
$vars = new Vars([
    __DIR__.'/config/config.yml',
    __DIR__.'/sub/config.yml',
    ]);

将同时使用 __DIR__.'/config' 作为 path

变量

您可以在 Vars 中使用 3 种类型的变量:替换文件内环境,语法如下

为了提高可读性,您还可以在变量名和前缀/后缀之间放置空格,如下所示

replacement_variable: % VARIABLE %
infile_variable: %$ VARIABLE %
env_variable: %^ VARIABLE %
替换

替换变量从 Vars 外部加载,因此它通常用于 PHP 函数/逻辑,例如 __dir__

test_key_1: %foo%
test_key_2: /bar/%foobar%/bar
$vars = new Vars(__DIR__.'/config/config.yml', [
    'replacements' => [
        'foo' => 'bar',
        'foobar' => 'barfoo'
    ],
]);

输出

[
    "test_key_1" => "bar",
    "test_key_2" => "/bar/barfoo/foobar/"
]

您的替换必须以前缀和后缀 % 开头和结尾

您还可以从文件中加载变量

$vars = new Vars(__DIR__.'/config/config.yml', [
    'replacements' => __DIR__.'/config/variables.yml'
]);
文件内变量

您还可以使用文件中已定义的键的变量,例如

test_key_1: hello
test_key_2: /bar/%$test_key_1%/bar

输出

[
    "test_key_1" => "bar",
    "test_key_2" => "/bar/hello/foobar/"
]

您的替换必须以前缀 %$ 开头,以 % 结尾。

对于 in-filereplacements,您可以使用点表示法语法来获取数组,例如

test_key_1: 
    test_key_2: hello
test_key_3: /bar/%$test_key_1.test_key_2%/bar

输出

[
    "test_key_1" => array(
        "test_key_2" => "hello"
    ),
    "test_key_2" => "/bar/hello/foobar/"
]
环境变量

您还可以使用环境变量来进行替换

test_key_1: %^DATABASE_USERNAME%
test_key_2: %^DATABASE_PASSWORD%
# nginx config example
location @site {
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    include fastcgi_params;
    fastcgi_param  SCRIPT_FILENAME $document_root/index.php;

    # env variables
    fastcgi_param DATABASE_USERNAME test_username;
    fastcgi_param DATABASE_PASSWORD test_password;
}

输出

[
    "test_key_1" => "test_username",
    "test_key_2" => "test_password"
]

您必须以前缀 %^ 和后缀 % 开头和结尾您的环境变量

您还可以设置配置数组以供 getenv() 使用

$vars = new Vars(__DIR__.'/config/config.yml');
$vars->toEnv();

注意:您的配置将展平为点表示法,例如

test_key_1:
    test_key_2: value

将通过

getenv('test_key_1.test_key_2'); // value

全局变量

Vars 中的 Globals 指的是定义为这样的变量

_globals:
    test_key_1: test_value_1

基本上它们只是封装在一个 _globals 数组中 -- 使用这些变量的目的是您可以通过 Vars 中的 getGlobals() 访问它们

默认操作是将它们合并到其他文件内容中,因此

_globals:
    test_key_1: test_value_1
test_key_2: test_value_2

变为

[
    'test_key_1' => 'test_value_1',
    'test_key_2' => 'test_value_2',
]

但是,您可以通过将选项中的 merge_globals 更改为 false 来覆盖此操作。

如果您不理解这一点,那么您可能根本不需要使用全局变量,但它们对于与封装在例如 $app 下的框架一起使用非常有用,并且您想要能够以如下方式访问一些键 => 值:$app['test_key_1']。请参阅 Silex 提供程序部分以获取更多示例。

缓存

Vars 会自动将资源缓存 5 分钟,您可以通过将 cache 选项设置为 false 来关闭此功能。

如果未设置 cache_path,则将其设置为 path 设置的值。必须可写 cache_path

要使缓存失效,只需删除 cache_path 中名为 vars 的文件夹即可,例如:rm -rf /var/www/application/app/cache/vars

由于 opcache 的额外加速,缓存文件是一个 .php 文件。

如果您正在使用Silex提供程序,那么在调试模式下,将不会使用或设置缓存。

加载器

加载器使得Vars能够读取不同的文件类型(默认为Ini、Json、Php、Tomm、Xml和Yaml)。

您可以通过选项启用和禁用加载器。

默认加载所有默认加载器。

$vars = new Vars(__DIR__.'/config/config.yml', [
    'loaders' => 'default'
]);

// You can load individual loaders:
$vars = new Vars(__DIR__.'/config/config.yml', [
    'loaders' => [
        'ini',
        'json'
    [
]);

//You can also create and load custom loaders:
$vars = new Vars(__DIR__.'/config/config.yml', [
    'loaders' => [
        '\Foo\Bar\CustomFooBarLoader',
        'ini',
        'json'
    ]
]);

要创建自己的自定义加载器,您必须扩展M1\Vars\Loader\AbstractLoader,在public static $supported数组中包含支持的扩展,并有一个public function load()函数来加载文件的內容。

以下是一个加载.txt文件的简单示例

namespace M1\Foo\Bar\Loader;

use M1\Vars\Loader\AbstractLoader;

class TextLoader extends AbstractLoader
{
    public static $supported = array('txt');

    public function load()
    {

        $content = [];

        foreach (file($this->entity) as $line) {
            list($key, $value) = explode(':', $line, 2);
            $content[trim($key)] = trim($value);
        }

        $this->content = $content;

        return $this;
    }
}

然后要使用这个加载器,您只需这样做

$vars = new Vars(__DIR__.'/config/config.yml', [
    'loaders' => [
        '\M1\Foo\Bar\Loader\TextLoader',
    ]
]);

注意:请不要在实际中使用此加载器,它仅用于展示目的。

提供者

Silex

使用Silex库非常简单,只需在注册其他服务提供程序时注册它即可。

$app->register(new M1\Vars\Provider\Silex\VarsServiceProvider('example.yml'), [
    'vars.path' => __DIR__.'/../../app/config/test/',
    'vars.options' => [
        'cache' => true,
        'cache_path' => __DIR__.'/../../app/config/cache/',
        'cache_expire' => 500,
        'replacements' => [
            'test' => 'test_replacement'
        ],
        'loaders' => [
            'yml',
            'json'
        ],
        'merge_globals' => true,
        'replacements' => __DIR__.'/../../app/config/replacements.json',
    ]]);

然后您可以从$app['vars']访问您的配置。

注意:如果$app['debug'] = true,则不会使用缓存。

您也可以使用点表示法从$app中访问配置值,例如

test_key_1:
    test_key_2: value
test_key_3: value

您可以使用点表示法获取以上内容,如下所示

$app['vars']['test_key_1.test_key_2']; // value
$app['vars']['test_key_3']; // value

您还可以将全局变量合并到$app中,如下所示

# example.yml
_globals:
    monolog.logfile: log.log
test_key_1: test_value_2
$app->register(new M1\Vars\Provider\Silex\VarsServiceProvider('example.yml'));

// register monolog here and other service providers

$app['vars.merge']();

注意$app['vars.merge']() - 这将覆盖服务提供程序默认设置,因此在本例中,monolog将使用vars配置中定义的日志文件。

您必须在您的配置中为提供配置值的服务提供程序调用vars.merge之后调用。

您还可以通过$app['vars.test_key_1']访问test_key_1,如果要这样做,您可以像这样访问全局变量$app['monolog.logfile']

公共 API

Vars

Vars($resource, $options = array())

创建新的Vars配置的构造函数

$vars = new Vars(__DIR__.'/config/config.yml', [
    // this will affect how you getResource() and will  default to the path
    // of the first resource you initiate
    'path' => __DIR__.'/config',

    // to cache or not -- defaults to true
    'cache' => true,

    // where the cache is stored -- If not set will default to the base path
    'cache_path' => __DIR__.'/config/',

    // How long the cache lasts for -- Defaults to 300 seconds (5 minutes)
    'cache_expire' => 300,

    // Replacement variables -- see variables section for more detail
    'replacements' => [
        'foo' => 'bar',
        'foobar' => 'barfoo'
    ],

    // The file loaders to load the configs -- see loader section for more detail
    'loaders' => [
        'default'
    ]
]);
getContent()

返回所有配置的解析內容。

getResource($resource)

获取指定资源,返回文件资源或如果资源不存在则返回false。

$resource名称基于在基础路径中定义的路径和文件名。

# example.yml
imports: example2.yml
test_1: value

# example2.yml
test_2: value
$vars = new Vars('example.yml');
$vars->getResource('example2.yml'); // FileResource

$vars->getResource('example2.yml')->getContent();
# output:
# [
#     "test_2" => "value"
# ]
getResources()

返回导入的所有资源,它们将是FileResource对象。

toEnv()

使得配置可通过getenv()访问。

$vars = new Vars('example.yml');
$vars->toEnv();

getenv('test_1'); // value
toDots()

使得配置可以扁平化为点表示法数组。

test_value_1:
    test_value_2: value
    test_value_3: value
$vars = new Vars('example.yml');
$vars->toDots();
# output:
# [
#     "test_value_1.test_value_2" => "value",
#     "test_value_1.test_value_3" => "value
# ]
getGlobals()

获取在_globals中定义的值。

set($key, $value)

设置配置键。

$vars = new Vars('example.yml');
$vars->set('test_key_1', 'value_2');
get($key)

获取配置键。

$vars = new Vars('example.yml');
$vars->get('test_key_1'); // value

FileResource

getRawContent()

从文件获取原始、未解析的內容。

# example.yml
test_value_1:
    imports: example2.yml
test_value_2: %root%/foo/%dir%
$vars = new Vars('example.yml');
$vars->getResource('example.yml')->getRawContent();
# output:
# [
#     test_value_1:
#          imports: example2.yml
#     test_value_2: %root%/foo/%dir%
# ]
getContent()

请参阅getContent()

get($key)

请参阅get()

待办事项

  • 添加更多提供程序(Symfony、Laravel等)

变更日志

请参阅变更日志了解最近有哪些更改。

测试

$ composer test

贡献

请参阅贡献以获取详细信息。

安全

如果您发现任何与安全相关的问题,请通过电子邮件hello@milescroxford.com联系,而不是使用问题跟踪器。

致谢

许可证

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