alius / config
包含php数组文件
1.0
2016-01-17 21:32 UTC
Requires
- php: >=5.5
This package is not auto-updated.
Last update: 2024-09-20 22:37:25 UTC
README
Alius Config
Alius Config只是一个简单的composer包,它所能做的就是包含php数组文件。
不要将任何敏感信息提交到你的版本控制中!
基本用法
<?php
return [
'test' => 'this is a test',
];
$config = new \Alius\Config\Config('path_to_file.php');
print $config->get('test'); // => this is a test
多个文件和目录
你可以包含多个文件
$config = new \Alius\Config\Config([
'path_to_file1.php',
'path_to_file2.php',
]);
一个或多个目录(递归包含子目录和文件)
$config = new \Alius\Config\Config([
'path_to_directory',
'path_to_directory2',
]);
所有文件必须使用php作为扩展名,并且必须返回数组。
最后一个文件优先
如果你包含两个具有相同变量的文件,则最后一个文件总是优先
<?php
// file1.php
return [
'test' => 'one',
];
<?php
// file2.php
return [
'test' => 'two',
];
$config = new \Alius\Config\Config(['file1.php', 'file2.php']);
print $config->get('test'); // => two
建议以数字开头命名文件
10-something.php
20-something_more.php
获取变量的源文件
包含大量文件可能会很混乱,因此你可以获取变量的源文件
print $config->getOrigin('test'); // => file2.php
必需变量
你可以标记变量为必需,如果没有包含的文件包含此变量,则将抛出异常
$config = new \Alius\Config\Config('path_to_file.php', ['test']);
var_dump($config->isRequired('test')); // => true
var_dump($config->isRequired('test2')); // => false
在一个数组中获取变量
你可以获取包含所有变量的数组
$config->compile();
如果发生错误
- 任何文件不存在或不可读,或扩展名不是php
- 如果你尝试获取一个不存在的变量(例如
$config->get('not_there');
或$config->getOrigin('not_there');
) - 当在包含的任何文件中找不到必需变量时
重点是它应该快速失败,这样你就可以在提交更改或部署之前修复所有内容。
推荐用法
不要将任何敏感信息提交到你的版本控制中!
你应该为所有非敏感数据创建一个目录,并为敏感数据创建另一个目录(并将该目录排除在版本控制之外)。
例如
config/non-sensitive-data1.php
config/non-sensitive-data2.php
exclude_this_dir_from_vc/database.php
或者,你仍然可以使用dotenv或类似的工具处理敏感数据,例如Laravel的env函数和默认值
return [
'db_host' => env('db_host', 'localhost'),
'db_user' => env('db_user', 'homestead'),
'db_pass' => env('db_pass', 'secret'),
'db_name' => env('db_name', 'homestead'),
];
dotenv有什么问题?
没有问题,但有时它可能不足以满足需求。
使用这个包,你可以有条件地包含文件,覆盖变量,你可以使用bool、int、float、数组、常量、闭包,甚至对象或资源。
或者,你可以扩展它,创建自己的DatabaseConfig类,然后将其作为依赖项注入。