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