apolinux / config
使用点路由管理配置
v0.6
2023-10-17 13:50 UTC
Requires
- php: >7.4
Requires (Dev)
- phpunit/phpunit: >=9.0
README
在文件内以字典风格数组设置或获取配置项。
配置存储在一个包含必须返回的数组的文件中。
// file called config.php
return [
'item1' => 'value1' ,
'item2' => [
'item3 => 'value2',
],
..
];
然后可以使用点表示法获取数组内的项目,例如,对于item3
$result = Config::get('config.item2.item3');
表示法中的第一部分 'config' 是不带.php扩展名的文件名。
安装
composer require apolinux/configfile
示例
在当前目录下有一个名为myconfig.php的php文件,其中包含以下代码
// myconfig.php
return [
'item' => ['item2' => ['item3' => ['item4' => ['http://uno']]]],
'list' => ['blablabla'],
'other' => ['a' => 'b', 'c' => 'd', 'e' => 'f'],
'alt' => ['alt1' => ['ttt ' => [1, 2, 3, 4, 5, 10000]]],
];
然后我们获取项目
<?php
Config::init(__DIR__) ;
echo Config::get('myconfig.item.item2.item3.item4');
// it shows 'http://uno'
echo Config::get('myconfig.list');
// shows 'blablabla'
echo Config::set('myconfig.list','otherlist');
// set only in memory 'otherlist' in 'list' key from myconfig.php file
方法
init($dir_base)
定义配置文件的基目录
get($item, $default=null)
从定义在 $item 中的键获取值。如果没有找到值,则返回 $default。如果 $default 为空,则抛出异常
set($item, $value)
将值放入键 $item 中,但仅在内存中。配置文件保持不变。
getToUserPwd($item, $default=null)
将键和值组合在同一文本中。将索引数组如 ['a' => 'b'] 转换为形式 'a:b'。
getReplaced($item, $default=null)
像 get() 方法一样获取项,但将返回值中的通配符(如 '%item%')替换为使用此通配符进行的另一个 get 操作获取的值。
示例:如果 Config::get('config.testwc') 返回 '%init%/some',则 getReplaced 搜索 Config::get('config.init') 的值并在 '%init%' 中替换它
configlist
configlist 是一个脚本,显示配置文件中的所有配置,每行一个项目。安装在目录 vendor/bin 中。
configlist --help
List configuration files in lineal form like:itema.itemb.itemc => value
Usage configlist <base_dir> <config_file>
Where
base_dir : optional. base directory where to find for configuration files, default directory is current.
config_file: optional. write configuration file name without php, example: config