使用 php 自动加载 Ajax 个文件的组织

Organization of Ajax files for autoloading with php

我想在我的 php 项目中使用自动加载器,但我不知道我的文件组织是否可行。现在我的文件夹结构是这样的:

-ProjectFolder
   index.php
   -common
      -ajax
         ajax_file.php
      -classes
         MyClass.php

在 MyClass.php 中,我有以下代码行 namespace common\classes;

在 index.php 我有

spl_autoload_register(function ($class_name){
  $file = str_replace('\', '/', $class_name);
  require "$file.php";
});

所以我可以在 index.php 文件中调用 "test" 静态方法,方法是在我的代码中添加以下行: common\classes\MyClass::test();

但是 index.php 用于从 ajax_file.php 获取答案。 如果我只是通过将同一行代码添加到 ajax_file.php 来调用我的 "test" 方法,它会告诉我找不到 class。我想这是因为它是独立于 index.php.

中发生的事情加载的

我不知道如何从 ajax_file.php 访问 MyClass,而且我什至不确定是否可行,因为我读过一些似乎表明无法访问 "go back" 的内容在自动加载器中使用“../”。

你能告诉我这样做的好方法吗?

您必须确保您的自动加载器使用绝对路径而不是相对路径。 这涉及为对应于 projectFolder.

的根名称空间定义基本目录

在index.php中:

spl_autoload_register(function ($class_name) {
    $file = __DIR__ . '/' . str_replace('\', '/', $class_name);
    require "$file.php";
});

您在 php-fig 上有一些自动加载器示例,以符合标准 (PSR-4)。

请注意 ajax_file.php 文件必须明确包含自动加载器(因此 index.php