yosymfony / config-loader
配置文件加载器
v2.0.0
2018-09-02 15:36 UTC
Requires
- php: >=7.2
Requires (Dev)
- phpunit/phpunit: ^7.1
- symfony/yaml: ^4.1
- yosymfony/toml: ^1.0
Suggests
- symfony/yaml: ^4.1
- yosymfony/toml: ^1.0
README
一个通用的配置加载器,内置对 YAML、TOML 和 JSON 的支持。
安装
需要 PHP >= 7.2。
使用 Composer 安装此包
composer require yosymfony/config-loader
用法
初始化
类 ConfigLoader
允许您加载配置资源。它期望在构造函数中提供一个加载器列表,因此您可以仅传递您需要的那些
use Yosymfony\ConfigLoader\FileLocator; use Yosymfony\ConfigLoader\ConfigLoader; // The file locator uses an array of pre-defined paths to find files: $locator = new FileLocator(['/path1', '/path2']); // Set up the ConfigLoader to work with YAML and TOML configuration files: $config = new ConfigLoader([ new YamlLoader($locator), new TomlLoader($locator), ]);
可用的加载器
Yaml 加载器
要求: Symfony YAML 组件
composer require symfony/yaml
初始化
$config = new ConfigLoader([ new YamlLoader($locator), ]);
Toml 加载器
要求: Toml 组件
composer require yosymfony/toml
初始化
$config = new ConfigLoader([ new TomlLoader($locator), ]);
Json 加载器
初始化
$config = new ConfigLoader([ new JsonLoader($locator), ]);
加载配置文件
// Search this file in "path1" and "path2": $config->load('user.yml'); // or load a file using its absolute path: $config->load('/var/config/user1.yml');
.dist 文件
此库支持 .dist
文件。文件名按照以下层次结构解析
- filename.ext
- filename.ext.dist(如果
filename.ext
不存在)
加载内联配置
要解析内联配置,只需将配置文本作为第一个参数而不是文件名,并将格式类型作为第二个参数即可
$repository = $config->load('server: "your-name.com"', YamlLoader::TYPE);
导入文件
此库支持导入文件。以下示例展示了如何使用 YAML 语法导入三个文件
--- imports: - config-imported.yml - config-imported.toml - config-imported.json
使用 JSON 语法的类似示例
{ "imports": [ "config.json" ] }
使用 TOML 语法的示例
imports = [
"config.toml"
]
仓库
配置文件被加载到仓库中。仓库是一个实现了 ArrayAccess 接口 的包装器,并公开了用于处理配置值的方法。
// Returns the value associeted with key "name" or the default value in case not found $repository->get('name', 'default'); // Do the same that the previous sentence but using array notation $repository['name'];
操作
联合
您可以执行仓库 A 和另一个 B 的联合,结果为 C
$resultC = $repositoryA->union($repositoryB);
$repositoryB
的值比 $repositoryA
中的值优先级低。
交集
您可以执行仓库 A 和另一个 B 的交集,结果为 C
$resultC = $repositoryA->intersection($repositoryB);
$repositoryB
的值比 $repositoryA
中的值优先级低。
创建空白仓库
创建空白仓库非常简单。您只需要创建一个 Repository
类的实例
use Yosymfony\Config-loader\Repository; //... $repository = new Repository([ 'name' => 'Yo! Symfony', ]); $repository->set('server', 'your-name.com');
单元测试
您可以使用以下命令运行单元测试
$ cd toml $ composer test
许可协议
此库是开源软件,许可协议为 MIT 许可协议。