Using the spl_autoload_register(), should I use a single autoload function that contains all the logic to determine where the include files are or should I break each include grouping into it's own function with it's own logic to include the files for the called function? As the places where include files may reside expands so too will the logic of a single function. If I break it into multiple functions I can add functions as new groupings are added, but the functions will be copy/pastes of each other with minor alterations.
Currently I have a tool with a single registered autoload function that picks apart the class name and tries to predict where it is and then includes it. Due to naming conventions for the project this has been pretty simple.
if has namespace
if in template namespace look in Root\Templates
else look in Root\Modules\Namespace
else
look in Root\System
if file exists include
But we are starting to include Interfaces and Traits into our codebase and it hurts me to include the type of a thing in it's name. So we are looking at instead of a single autoload function that digs through the class name and looks for the file and has increasingly complex logic to it, we are looking at having multiple autoload functions registered. But each one follows the same pattern and any time I see that I get paranoid about code copying.
function systemAutoloadFunc
logic to create probable filename
if filename exists in system include it and return true
else return false
function moduleAutoloadFunc
logic to create probable filename
if filename exists in modules include it and return true
else return false
Every autoload function will follow that pattern and the last of each function if filename exists, include return true else return false is going to be identical code. This makes me paranoid about having to update it later across the board if the file_exists include pattern we are using ever changes. Or is it just that, paranoia and the multiple functions with some identical code is the best option?
Best Answer
Registering multiple autoloaders lets you separate different naming conventions for directory and file names and will be easier to maintain in the long run.
Imagine needing to add or remove functionality for the autoloader. Should you need to dive into a monolithic function or simply tweak or add a smaller function?
Similar calls to "file_exists() / include() / return" can be put into a helper function instead of copypasting that code.
Registering different ones also gives you easier control over what order they are invoked. For example, if you want to have a master override directory, you would register that first.
From the manual: http://php.net/manual/en/function.spl-autoload-register.php