在php中加载文件之前自动选择文件位置


Automatically choose a file location before loading it in php

我需要创建一个简单的文件重载系统,就像symfony对php文件和模板所做的那样。我将举一个例子来解释我需要什么:

给定此文件夹结构:

 - root_folder
    - modules
       -module1
         -file1.php
         -file2.php
         -file3.php
    - specific_modules
       -module1
         -file2.php

我想找到一种方法,如果在调用时在specific_modules文件夹(file2.php(中找到文件,则自动加载该文件;如果没有找到,则应正常从模块目录加载file2.php。

我想为程序员做这件事,但不确定这是否可能!!

欢迎任何帮助或建议,提前感谢!

skarvin

如果文件只包含具有相同名称的对象,那么您可以编写自己的自动加载器函数并将其注册到spl_autoload_register()。也许类似

function my_loader($class)
{
    // look in specific_modules dir for $class
    // if not there, look in modules dir for $class
}
spl_autoload_register('my_loader');

这将允许您简单地编码为:

$obj = new Thing();

如果Thing是在specific_modules中定义的,它将使用那个,否则就是默认的。

$normal_dir = 'modules';
$specific_dir = 'specific_modules';
$modules = array('module1' => array('file1.php','file2.php','file3.php'));
foreach($modules as $module => $files)
{
    foreach($files as $file)
    {
        if(!file_exists("$specific_dir/$module/$file"))
        {
            include("$normal_dir/$module/$file");
        }
        else
        {
            include("$specific_dir/$module/$file");
        }
    }
}

这段代码将尽可能简单地为您工作,它可以轻松地将新文件添加到模块中并更改目录名。我所说的"负载"是指假设包含,但这一部分很容易更改。

与Alex的答案类似,您也可以定义一个__autoload函数:

function __autoload($class_name) {
    if (file_exists(__DIR__ . '/specific_modules/' . $class_name . '.php')) {
        require __DIR__ . '/specific_modules/' . $class_name . '.php';
    }
    elseif (file_exists(__DIR__ . '/modules/' . $class_name . '.php')) {
        require __DIR__ . '/modules/' . $class_name . '.php';
    }
    else {
        // Error
    }
}

然后,如果您执行$obj = new Thing();,它将尝试从这两个目录加载Thing.php