phrity/config

配置接口、类和工厂

1.3.0 2024-06-07 11:47 UTC

This package is auto-updated.

Last update: 2024-09-08 09:19:51 UTC


README

Build Status Coverage Status

简介

处理配置的工具。接口、实现类、各种读取器和工厂。

安装

使用 Composer 安装;

composer require phrity/config

ConfigurationInterface 接口

Phrity\Config\ConfigurationInterface 扩展了 PSR-11 ContainerInterfaceJsonSerializable 接口。

// ContainerInterface implementation
public function get(string $id): mixed;
public function has(string $id): bool;

// JsonSerializable implementation
public function jsonSerialize(): mixed;

// Additional methods
public function __construct(object|array $config);
public function merge(ConfigurationInterface $config): ConfigurationInterface;

Configuration

Phrity\Config\Configuration 类实现了 ConfigurationInterface

use Phrity\Config\Configuration;

// Initiate with object or associative array
$config = new Configuration([
    'a' => 23,
    'b' => [
        'bb' => 66,
    ],
]);

// Check and get (case insensitive) from configuration
$config->has('a'); // => true
$config->get('a'); // => 23

// Trying to get non-exising configuration will throw exception
$config->has('c'); // => false
$config->get('c'); // throws NotFoundException

通过路径访问

// It is possible to access by path
$config->has('b/bb'); // => true
$config->get('b/bb'); // => 66

指定默认值

// If default is specified, non-exising configuration will return that value instead of throwing exception
$config->get('a', default: 99); // => 23
$config->get('c', default: 99); // => 99

类型强制转换

// Some types can be coerced into another type
$config->get('a', coerce: 'string'); // => "23"
  • 目标类型 boolean
    • 00.0"0""0.0""""false"null 将被强制转换为 false
    • 11.1"1""1.0""true" 将被强制转换为 true
  • 目标类型 integerdouble
    • 数值 string 将被强制转换为 integerdouble
    • nullfalse 将被强制转换为 00.0
    • true 将被强制转换为 11.0
  • 目标类型 string
    • integerdouble 将被强制转换为数值 string
    • null 将被强制转换为 "null"
    • false 将被强制转换为 "false"
    • true 将被强制转换为 "true"
  • 目标类型 null
    • 00.0"0""0.0""""null"false 将被强制转换为 null

未指定上述任何强制转换将导致 CoercionException

合并配置

// Configurations can be merged (immutable, new instance will be returned)
$additional = new Configuration(['c' => 12, 'b' => ['bc' => 13]]);
$merged = $config->merge($additional);

读取器类

提供多种配置读取器。

ConfigurationFactory

Phrity\Config\ConfigurationFactory 提供创建和合并配置的快捷方式。

$factory = new Phrity\Config\ConfigurationFactory();

$configData = $factory->fromData(data: ['a' => 23]);
$configJson = $factory->fromJson(json: '{"a": 23}');
$configJsonFile = $factory->fromJsonFile(path: 'path/to/config.json');
$configYaml = $factory->fromYaml(yaml: 'n: 23');
$configYamlFile = $factory->fromYamlFile(path: 'path/to/config.yaml');
$configEnv = $factory->fromEnv();
$configEnvFile = $factory->fromEnvFile('.env');

$configMerged = $factory->merge(
    $configData,
    $configJson,
    $configJsonFile,
    $configYaml,
    $configYamlFile,
    $configEnv,
    $configEnvlFile,
);

版本