Search code examples
phpwordpressautoloader

Class autoloader in wordpress plugin


I want to write a class autoloader to use in a wordpress plugin. This plugin will be installed on multiple sites, and i want to minimize the chance of conflicts with other plugins.

The autoloader will be something like this:

function __autoload($name) {
    //some code here
}

My main issue is, what happens if another class also uses a function like this? I think it will be bound to give problems. What would be the best way to avoid something like that?

I am trying to not use namespaces so the code will also work on previous versions of php.


Solution

  • Use some implementation like this one.

    function TR_Autoloader($className)
    {
        $assetList = array(
            get_stylesheet_directory() . '/vendor/log4php/Logger.php',
            // added to fix woocommerce wp_email class not found issue
            WP_PLUGIN_DIR . '/woocommerce/includes/libraries/class-emogrifier.php'
            // add more paths if needed.
        );
    
    // normalized classes first.
        $path = get_stylesheet_directory() . '/classes/class-';
        $fullPath = $path . $className . '.php';
    
        if (file_exists($fullPath)) {
            include_once $fullPath;
        }
    
        if (class_exists($className)) {
            return;
        } else {  // read the rest of the asset locations.
            foreach ($assetList as $currentAsset) {
                if (is_dir($currentAsset)) {
                   foreach (new DirectoryIterator($currentAsset) as $currentFile) 
    {
                        if (!($currentFile->isDot() || ($currentFile->getExtension() <> "php")))
                            require_once $currentAsset . $currentFile->getFilename();
                    }
                } elseif (is_file($currentAsset)) {
                    require_once $currentAsset;
                }
    
            }
        }
    }
    
    spl_autoload_register('TR_Autoloader');
    

    Basically this autoloader is registered and has the following features:

    • You can add a specific class file, if not following a specific pattern for the location of the files containing your classes (assetList) .
    • You can add entire directories to your search for your classes.
    • If the class is already defined, you can add more logic to deal with it.
    • You can use conditional class definition in your code and then override your class definition in the class loader.

    Now if you want want to do it in OOP way, just add the autoloader function inside a class. (ie: myAutoloaderClass) and call it from the constructor. then simply add one line inside your functions.php

    new myAutoloaderClass(); 
    

    and add in the constructor

    function __construct{
       spl_autoload_register('TR_Autoloader' , array($this,'TR_Autoloader'));
    }
    

    Hope this helps. HR