Search code examples
phpcomposer-phpautoloadautoloaderspl-autoload-register

How to autoload and call an independent PHP class without using require_once?


I have a main class called EQ, connected to other classes, and can be viewed in this GitHub link.

The EQ class is not connected to my composer, and I call it in local server using:

php -f path/to/EQ.php 

and live server using a CRON job:

1,15,30,45  *   *   *   *   (sleep 12; /usr/bin/php -q /path/to/EQ.php >/dev/null 2>&1)

I'm not sure how to correctly use an autoloader and load all dependent files to this class, and remove require_onces. I have tried and it does seem to be working:

spl_autoload_register(array('EQ', 'autoload'));

How do I solve this problem?

Attempt

//Creates a JSON for all equities // iextrading API
require_once __DIR__ . "/EquityRecords.php";
// Gets data from sectors  // iextrading API
require_once __DIR__ . "/SectorMovers.php";
// Basic Statistical Methods
require_once __DIR__ . "/ST.php";
// HTML view PHP
require_once __DIR__ . "/BuildHTMLstringForEQ.php";
// Chart calculations
require_once __DIR__ . "/ChartEQ.php";
// Helper methods
require_once __DIR__ . "/HelperEQ.php";

if (EQ::isLocalServer()) {
    error_reporting(E_ALL);
} else {
    error_reporting(0);
}

/**
 * This is the main method of this class.
 * Collects/Processes/Writes on ~8K-10K MD files (meta tags and HTML) for equities extracted from API 1 at iextrading
 * Updates all equities files in the front symbol directory at $dir
 */

EQ::getEquilibriums(new EQ());

/**
 * This is a key class for processing all equities including two other classes
 * Stock
 */
class EQ
{



}

spl_autoload_register(array('EQ', 'autoload'));

Solution

  • Essentially your autoloader function maps a class name to a file name. For example:

    class EQ
    {
        public function autoloader($classname)
        {
            $filename = __DIR__ . "/includes/$classname.class.php";
            if (file_exists($filename)) {
                require_once $filename;
            } else {
                throw new Exception(sprintf("File %s not found!", $filename));
            }
        }
    }
    
    spl_autoload_register(["EQ", "autoloader"]);
    
    $st = new ST;
    // ST.php should be loaded automatically
    $st->doStuff();
    

    But, most of this stuff is built into PHP, making your code even simpler:

    spl_autoload_extensions(".php");
    spl_autoload_register();
    $st = new ST;
    $st->doStuff();
    

    As long as ST.php is anywhere in your include_path it just works. No autoloader function needed.