As having all my files in the same app/ directory was a bit limited, here’s what I’ve done to load all PHP files from a given directory and its sub-directories.
It means you don’t care about loading order. If you still want to use this but need some files before the custom directory files are loaded, use the array solution provided.
- Add a new auto-loaded file to my composer.json
"autoload": { "psr-4": { "App\\": "app/" }, "files": [ "app/lib-autoload.php" ] }
- Create the app/lib-autoload.php
glob_recursive needed to load recursively (source)
if ( ! function_exists('glob_recursive'))
{
// Does not support flag GLOB_BRACE
function glob_recursive($pattern, $flags = 0)
{
$files = glob($pattern, $flags);
foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir)
{
$files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));
}
return $files;
}
}
//$files = glob(__DIR__ . '/lib/**/*.php'); //will only load first level sub-dir
$files = glob_recursive(__DIR__ . '/lib/*.php');
if ($files === false) {
throw new RuntimeException("Failed to glob for function files");
}
foreach ($files as $file) {
require_once $file;
}
unset($file, $files);
- all PHP files within app/lib/ directories and sub-directories will be loaded.