php 用于搜索不带扩展名的文件名的路径的函数

php function to search paths for filename WITHOUT extension

好的,所以我正在做一个配置 class,它将在 4 个主要位置使用一组不同的文件类型。现在我想这样做,以便配置 class 将在我使用以下

时按顺序搜索这些位置
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");
                }
            }
        }
    }

相当凌乱而且不太灵活。

我想要做的是仅在找到第一个匹配项后按文件名以相同的顺序搜索位置然后它将 return 具有配置扩展名的文件 class 使用正确的方法解析成 php 数组等等。

在这些位置搜索文件名的最佳方法是什么

例子 假设我们想要一个数据库配置文件,你可以看到有 2

ConfigLocation1/Dev/
   /file.php
   /database.json
ConfigLocation1/
   /database.ini
   /anotherfile.json

我想像这样使用这个功能

config::findFile('database');

它return

$result = ConfigLocation1/Dev/database.json

但如果在这里找不到,那么

$result = ConfigLocation1/database.ini

不太擅长解释事情所以希望这个例子对你有帮助

正如您提到的,您需要在 4 个位置检查文件,因此创建一个目录数组并循环遍历,而不是 if 条件。

并且您可以使用 glob 来查找文件而不考虑扩展名。请参阅下面的示例:-

//Make a array of directory where you want to look for files.
$dirs = array(
    ROOT . DS . 'Application/Config/' . APP_ENV . DS,
    CARBON_PATH . 'Config' . DS . APP_ENV . DS
);

function findFiles($directory, $filename){
    $match = array();

    foreach ($directory => $dir) {
        $files = glob($dir.$filename);
        foreach ($files as $file) {
             $match[] = $file;
        }

    }

    return $match;
} 

// to find database
$results = findFiles($dirs, 'database.*');