After doing much reading of the PHP docs and trying out other developers' autoloader code, below is what I've come up with for an autoloader. It is working as expected so far. Posting the code here to gather review/feedback from peers. Here are some questions that come to mind -
- How can it be improved?
- Are there any potential issues?
- Are there any ways to make it more concise without sacrificing readability?
// ROOT is used in multiple places in the app, thus the constant
define('ROOT', $_SERVER['DOCUMENT_ROOT'] . '/MyApp/');
# autoloader
// recurses through project directory and builds associative array with file name as key and fully qualified file name as value (restrictions: file names end with .php, exclude index.php)
// autoloader function loads class files by matching class name to file name key in array to get path value
// note: RecursiveIteratorIterator returns an associative array with fully qualified file name as key and SplFileInfo Object as value
$projectDirectory = ROOT;
$ignore = ['.git','_Logs'];
$directory = new RecursiveDirectoryIterator($projectDirectory, RecursiveDirectoryIterator::SKIP_DOTS);
$directory = new RecursiveCallbackFilterIterator($directory, fn($current) => !in_array($current->getFilename(), $ignore));
$objects = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::LEAVES_ONLY);
foreach (iterator_to_array($objects) as $fullFileName => $splFileInfoObject) {
$fileNameWithExtension = $splFileInfoObject->getfileName();
if (substr($fileNameWithExtension, -4) == '.php' && $fileNameWithExtension != 'index.php') {
$fileName = pathinfo($fileNameWithExtension, PATHINFO_FILENAME);
$files[$fileName] = $splFileInfoObject->getPathname();
}
}
// exit('<pre>' . print_r($files, 1) . '</pre>');
define('FILES', $files);
spl_autoload_register(fn($className) => require_once(FILES[$className]));
EDIT - The directory structure of this app is:
- Config
- Modules
- Utilities
Modules is where the business related files live. The Modules directory has a lot of activity during development with new subfolders being added frequently as new parts of the app are built. Thus the desire for an autoloader that can just recognize new subfolders and files.
Also, this app is not namespaced.