OOP项目的Autoloader

时间:2016-01-27 08:21:22

标签: php oop autoloader

我目前正在忙于一个大的WordPress插件,它包含几个类和接口(使用正确的命名空间)。从研究和我之前的问题得到的答案,最好的选择是使用界面注入(依赖注入)来维持SOC。这个阶段的一切都按预期工作。

我现在离开了把所有东西放在一个主要类中,它将用作控制器。此时,为了测试所有内容,我使用require_once来加载我的类和接口(文件位于名为functions 的文件夹中)

实施例

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

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

我的问题:

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

2 个答案:

答案 0 :(得分:2)

您可以使用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

答案 1 :(得分:1)

使用composer自动加载您的课程。它支持自动加载的命名空间,一旦设置,一切都将在他们自己的命名空间中自动完成。

你需要做的就是设置composer.json

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

只需要aotoload.php即可管理其他所有内容。

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