Pieter Goosen
Pieter Goosen

Reputation: 9941

Autoloader for OOP project

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

Upvotes: 2

Views: 835

Answers (2)

Charlie
Charlie

Reputation: 23798

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';

Upvotes: 1

Armen
Armen

Reputation: 4202

You can use 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` 

Check this article for more info: http://php.net/manual/en/language.oop5.autoload.php

Upvotes: 2

Related Questions