OOP 项目的自动加载器

Autoloader for OOP project

我目前正忙于一个大型 WordPress 插件,它由几个 classes 和界面组成(它们使用适当的命名空间)。根据研究和我从之前的问题中得到的答案,最好的选择是使用接口注入(依赖注入)来维护 SOC。此阶段的一切都按预期工作。

我现在需要将所有内容整合到一个主 class 中,它将用作控制器。此时,为了测试所有内容,我使用 require_once 来加载我的 classes 和接口( 文件位于名为 functions 的文件夹中)

示例:

require_once( '/functions/INTERFACEA.php' );
require_once( '/functions/CLASSA.php'     );
require_once( '/functions/INTERFACEB.php' );
require_once( '/functions/CLASSB.php'     );
//etc

我听说过自动加载器,但不完全了解如何在控制器中使用它们 class。我真正需要避免的一个问题是 class 在其接口之前加载,因为如果加载顺序错误,我会收到一个致命错误,指出我的接口不存在。

我的问题:

我如何正确使用控制器中的自动加载器 class 来加载我的 classes 和接口,这也确保我的接口在它们各自的 class 之前加载es

您可以使用spl_autoload_register

// Defining autoloader
spl_autoload_register(function ($class_name) {

    // just make sure here that $class_name is correct file name
    // and there is $class_name.php file if no the fix it 
    // E.G. use strtoupper etc.
    $class_name = strtoupper($class_name);

    require_once( '/functions/'.$class_name.'.php' );
});

// Then simply use 
$class = new CLASSA();
// if `CLASSA` implements `INTERFACEA` here php 
// will autoload `INTERFACEA.php` and `CLASSA.php` 

查看这篇文章了解更多信息:http://php.net/manual/en/language.oop5.autoload.php

使用 composer 自动加载您的 类。它支持用于自动加载的命名空间,并且一旦设置好,一切都将在它们自己的命名空间中简单地自动进行。

您只需完成设置 composer.json

"autoload": {
        "psr-4": {"Acme\": "src/"}
    }

只需要 aotoload.php,它将管理其他一切。

require __DIR__ . '/vendor/autoload.php';