volta-framework / component-configuration
提供配置管理的组件
v1.1.4
2023-10-15 13:41 UTC
Requires
- php: >=8.1
- volta-framework/component-cli: *
README
配置管理组件。
特性
- 不同格式:JSON 和 PHP 数组
- 文件或内存存储
- 级联配置
- 指定必需的选项
- 指定一组允许的选项(白名单)
- 基于代码中的配置键属性生成配置文件(*.json 或 *.php)
UML 类图
* UML 类图中仅显示最常用的类成员
* SPL = 标准PHP库
构建
declare(strict_types=1); use Volta\Component\Configuration\Config // i. Initialize a Config object with options stored in a *.php file $conf = new Config(__DIR__ . '/config/example-config.php'); // ii. Initialize a Config object with options stored in a *.json file $conf = new Config(__DIR__ . '/config/example-config.json'); // iii. Initialize a Config object with options stored in a json string $conf = new Config( '{ "databases": { "default": { "dsn": "sqlite:/path/to/sqlite/db/file.sqlite" } } }' ); // iv. Initialize a Config object with options stored in a php array $conf = new Config( [ 'databases' => [ 'default' => [ 'dsn' => 'sqlite:/path/to/sqlite/db/file.sqlite' ] ] ] ); // v. Adding or overwriting data after initialization can be done with the setOption() method // and accepts all the formats described above. Previous data will be // overwritten. (cascading) configuration $conf->setOptions(__DIR__ . '/config/example-config.php')
文件: ~/config/example-config.php
declare(strict_types=1); return [ 'databases' => [ 'default' => [ 'dsn' => 'sqlite:/path/to/sqlite/db/file.sqlite' ] ] ];
文件: ~/config/example-config.json
{
"databases": {
"default": {
"dsn": "sqlite:/path/to/sqlite/db/file.sqlite"
}
}
}
使用方法
初始化配置对象时,可以检索值。最好用示例代码展示
declare(strict_types=1); use Volta\Component\Configuration\Config use Volta\Component\Configuration\Exception as ConfigException use \PDO $conf = new Config(__DIR__ . '/config/example-config.php'); // check if we have a database configuration, exit if not if ($conf->hasOption('databases.default')) { exit('No default database settings configured') } // The above functionality can also be accomplished by adding (a) required option(s) which // will generate an exception on failure with the message: // // Required option "databases.default" is missing // try{ $conf = new Config( options: __DIR__ . '/config/example-config.php', requiredOptions: ['databases.default'] ); } catch (ConfigException $e) { exit($e->getMessage()) } // We also can set/overwrite a value $conf->setOption( key: 'database.default.password', value: null, overWrite: true ); // create PDO object and provide some defaults in case some options are not set $pdo = new PDO( dns: $conf['databases.default.dsn'], username: $conf->getOption('databases.default.username', null), password: $conf->getOption('databases.default.password'), options: $conf->getOption( 'databases.default.options', [ PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_CASE => PDO::CASE_NATURAL ] ) );