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 p
I recommend using namespaces, and PSR-4. You could simply copy this autoloader example from FIG.
But if you don't want to, you can use an autoloader like this one, that defines an convention for WP classes names, and uses that to find the class file.
So, for example, if you call a 'Main' class, then this autoloader will try to include the class file from path:
<plugin-path>/class-main.php
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:
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