comphp / config-json
提供处理JSON配置文件所需的功能
v0.1
2024-02-17 18:13 UTC
Requires
- php: ^8.3
- comphp/config: ^0.1
Requires (Dev)
- phpunit/phpunit: ^10.5.9
README
这个库提供了一个JSON配置驱动程序 JsonConfigurationDriver
,它实现了来自CommonPHP配置管理库的ConfigurationDriverContract
。它使得应用程序能够使用CommonPHP驱动管理系统无缝集成,以加载和保存JSON格式的配置。
功能
- 加载JSON配置:轻松地将JSON文件读取并解码为关联数组。
- 以JSON保存配置:将PHP关联数组序列化并保存回JSON格式的文件。
- JSON验证:在加载过程中确保JSON内容的完整性。
- 异常处理:对常见的JSON解析问题进行全面的错误和异常处理。
安装
使用Composer安装配置管理器和此驱动程序
composer require comphp/config
composer require comphp/config-json
用法
首先,确保您的DriverManager
实例配置为识别JSON驱动程序
use CommonPHP\Drivers\DriverManager; use CommonPHP\Configuration\Drivers\JsonConfigurationDriver\JsonConfigurationDriver; $driverManager = new DriverManager(); $driverManager->enable(JsonConfigurationDriver::class);
然后,当使用配置管理器加载或保存JSON文件时,由于#[ConfigurationDriverAttribute('json')]
属性,JsonConfigurationDriver
将自动用于.json
扩展。
加载配置文件
$configManager->loadDriver(JsonConfigurationDriver::class); $config = $configManager->get('path/to/configuration.json');
保存配置文件
确保已按照上述方式加载驱动程序,然后
$config->data['newKey'] = 'newValue'; $config->save(); // Saves the modifications back to 'path/to/configuration.json'
异常处理
- JsonException:如果JSON文件包含无效的JSON,则抛出。
- Exception:文件读写失败或JSON解码问题的通用异常。
此驱动程序为CommonPHP框架中基于JSON的配置提供了一种简单而强大的工作方式,确保了开发者的灵活性和易用性。