是的,所以我正在制作一个配置类,它将在4个主要位置使用不同文件类型的数组。现在我想这样做,以便配置类在我使用以下内容时按顺序搜索这些位置
if (file_exists(ROOT . DS . 'Application/Config/' . APP_ENV . DS . $file)) {
$this->filePath = ROOT . DS . 'Application/Config/' . APP_ENV . DS . $file;
echo $this->filePath;
} else {
if (file_exists(ROOT . DS . "Application/Config/$file")) {
$this->filePath = ROOT . DS . "Application/Config/$file";
echo $this->filePath;
} else {
if (file_exists(CARBON_PATH . 'Config' . DS . APP_ENV . DS . $file)) {
$this->filePath = CARBON_PATH . 'Config' . DS . APP_ENV . DS . $file;
echo $this->filePath;
} else {
if (file_exists(CARBON_PATH . "Config/$file")) {
$this->filePath = CARBON_PATH . "Config/$file";
echo $this->filePath;
} else {
throw new \Exception("Unable to locate: $file, Please check it exists");
}
}
}
}
非常凌乱,而且不够灵活。
我希望能够做的是在查找第一个匹配项后,按相同的顺序搜索位置按文件名称它将返回带有配置类扩展名的文件,以使用正确的方法解析为php数组等等。
在这些位置搜索文件名的最佳方法是什么
示例 假设我们想要一个数据库配置文件,你可以看到有2个
ConfigLocation1/Dev/
/file.php
/database.json
ConfigLocation1/
/database.ini
/anotherfile.json
我想使用像这样的功能
config::findFile('database');
然后返回
$result = ConfigLocation1/Dev/database.json
但如果没有找到,那么
$result = ConfigLocation1/database.ini
不太擅长解释事情所以希望这个例子有帮助
答案 0 :(得分:1)
正如您所提到的,您需要检查4个位置的文件,因此不是if条件,而是创建一个目录数组并循环遍历。
您可以使用glob查找文件而不考虑扩展名。请参阅下面的示例: -
print(timeit.timeit('testing(5)', 'from __main__ import testing', number=1000))