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条)

报告相同问题?

悬赏问题

  • ¥15 求指导ADS低噪放设计
  • ¥15 CARSIM前车变道设置
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存