🐘 从 JSON 文件中获取配置数据的 PHP 库

2.4.8 2023-10-04 11:56 UTC

This package is auto-updated.

Last update: 2024-09-22 09:13:30 UTC


README

🐘 从 JSON/yaml 文件中获取配置数据的 PHP 库

Latest Stable Version Source Code Software License Minimum PHP Version CI Status

设置

您可以使用 composer 安装

composer require davidlienhard/config:^2

注意:davidlienhard/config 需要 PHP 8.0

示例

设置

<?php declare(strict_types=1);
use DavidLienhard\Config\Config;

try {
    $config = new Config("path/to/config");
} catch (\Throwable $t) {
    echo "unable to setup config";
    exit(1);
}

读取数据

示例配置文件: system.json

{
    "name": "test",
    "list1": {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3",
        "key4": "value4"
    },
    "list2": [
        "value1",
        "value2",
        "value3",
        "value4"
    ]
}

获取单个值

<?php declare(strict_types=1);

echo $config->get("system", "name");
/* test */

echo $config->get("system", "list1", "key1");
/* value1 */

获取具有特定类型的单个值

<?php declare(strict_types=1);

echo $config->getAsString("system", "name");
/*
 if the value exists and is not an array, it will return a string in any case
 if the value is an array, this will throw an exception
 if the value does not exist this will return null
*/

以下方法也存在

  • getAsString()
  • getAsInt()
  • getAsFloat()
  • getAsBool()
  • getAsArray()

获取关联数组

<?php declare(strict_types=1);

print_r($config->get("system", "list1"));
/*
    Array
    (
        [key1] => value1
        [key2] => value2
        [key3] => value3
        [key4] => value4
    )
*/

获取数字数组

<?php declare(strict_types=1);

print_r($config->get("system", "list2"));
/*
    Array
    (
        [0] => value1
        [1] => value2
        [2] => value3
        [3] => value4
    )
*/

获取不存在的值

<?php declare(strict_types=1);

var_dump($config->get("system", "doesnotexist"));
/* NULL */

从不存在的文件中获取数据

<?php declare(strict_types=1);

var_dump($config->get("doesnotexist"));
/* throws \Exception */

解析器/支持的文件类型

默认情况下,此库包含两个解析器。一个是用于 Json,另一个是用于 Yaml/Yml 文件。如果需要,可以添加一个自定义解析器以支持其他文件类型,例如 XML 或 INI。自定义解析器必须扩展类 ParserAbstract 并实现接口 ParserInterface。解析器可以按以下方式注册

<?php declare(strict_types=1);

try {
    $config->registerParser(\your\custom\parser::class);
} catch (ConfigException $e) {
    die("unable to register custom parser");
}

异常

该库目前包含以下异常

  • Config - 所有其他异常的父异常
    • Conversion - 类型转换过程中发生的错误。例如,尝试将字符串转换为数组
    • Mismatch - 尝试访问不可用的配置数据
      • FileMismatch - 尝试访问不存在的文件
        • Parser - 解析文件时发生的错误。通常是通过无效的文件引起的
      • KeyMismatch - 尝试访问不存在的键,而文件是存在的

许可证

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