dpus81500574 2016-01-27 08:21
浏览 102
已采纳

OOP项目的Autoloader

I'm currently busy with a big WordPress plugin which consist of a couple of classes and interfaces (which use proper namespacing). From research and what answers I got from previous questions, the best option was to use interface injection (dependency injection) to maintain SOC. Everything at this stage work as intended.

I'm left now with bringing everything together into one main class which will be used as a contoller. At this moment, to test everything, I use require_once in order to load my classes and interfaces (files are in a folder called functions)

EXAMPLE:

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

I have heard about autoloaders, but does not completely understand how to use them in a controller class. One issue that I really need to avoid is that a class is loaded before its interface, because if the load sequence is wrong, I get a fatal error stating that my interface does not exist.

MY QUESTION:

How do I properly make use of an autoloader in a controller class to load my classes and intefaces which also makes sure that my interfaces are loaded before their respective classes

  • 写回答

2条回答 默认 最新

  • dqnrk44682 2016-01-27 08:30
    关注

    Use composer for autoloading your classes. It supports namespaces for autoloading and, once setup, everything would be simply automatic in their own namespaces.

    All you have to do it to setup the composer.json

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

    Just require the aotoload.php and it will manage everything else.

    require __DIR__ . '/vendor/autoload.php';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系