【问题标题】:autoloader works for files in root but not for files in subfolders自动加载器适用于根目录中的文件,但不适用于子文件夹中的文件
【发布时间】:2017-03-19 01:38:43
【问题描述】:

我在一个名为 config.php 的文件中有一个自动加载器,如下所示:

spl_autoload_register(function($className) {
    $className = ltrim($className, '\\');
    $fileName  = '';
    $namespace = '';
    if ($lastNsPos = strrpos($className, '\\')) {
        $namespace = substr($className, 0, $lastNsPos);
        $className = substr($className, $lastNsPos + 1);
        $fileName  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
    }
    $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
    require $fileName;
});

我的文件夹结构如下:

涂黑的文件夹是项目的名称。请注意,config.php 位于“includes”子文件夹中。它通过在脚本中包含 require_once ('includes/config.php'); 行来自动加载 index.php 的类。创建了一个新文件 functions.php 来处理与 AJAX 请求的数据库的通信。只要该文件位于项目根目录中并且require_once ('includes/config.php'); 包含在脚本中,自动加载器就可以正常工作。然而,当functions.php 被移动到一个子文件夹时,比如说js 子文件夹,并且require_once ('../includes/config.php'); 包含在脚本中,自动加载器就不起作用了。显示的错误信息是Warning: require(classes\model\Operation.php): failed to open stream: No such file or directory in C:\xampp\htdocs\xxxxx\OOP\includes\config.php on line 74。当functions.php位于子文件夹中时,为什么自动加载器不工作?我希望它适用于项目根目录中的文件和子文件夹中的文件。

【问题讨论】:

    标签: php


    【解决方案1】:

    这是我为这个问题提出的解决方案:

    1. 在 includes/config.php 文件中,将自动加载器更新为 PSR-4,请参见此处的关闭示例:https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md。匿名函数有一个名为 $base_dir 的变量。
    2. 创建了一个名为 root.php 的文件并将其存储在项目根目录中(与 index.php 相同的位置)。它包含以下内容:

    <?php
    # capture project's root directory
    // config.php, which is stored in a subfolder, requires this file so it knows this information
    // purpose of concatenating DIRECTORY_SEPARATOR is to add a slash to end of path
    $root = __DIR__ . DIRECTORY_SEPARATOR;
    ?>
    1. 在includes/config.php中,定义ROOT常量如下:

    <?php
    require (__DIR__ . '/../root.php');		// get project's root directory from file stored in root - this is needed to have access to the $root variable to create the ROOT constant in this script
    define ('ROOT', $root);				// this constant is used when in a file stored in a subfolder requires files stored in other subfolders
    ?>
    1. 在自动加载器中,位于 includes/config.php 中,设置 $base_dir 如下:$base_dir = ROOT . 'classes/';

    2. 在 js/functions.php 中包含的配置文件:require_once (__DIR__ . '/../includes/config.php');

    现在自动加载器适用于存储在根目录中的 index.php 和存储在 js 子文件夹中的 functions.php。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-07
      • 2014-05-25
      • 1970-01-01
      • 1970-01-01
      • 2018-04-08
      • 1970-01-01
      • 2015-05-23
      • 1970-01-01
      相关资源
      最近更新 更多