I currently am building my own PHP framework and am creating a lot of directories to store my classes in.
This is my current autoload function:
function __autoload($className)
{
$locations = array('', 'classes/', 'classes/calendar/', 'classes/exceptions/', 'classes/forms/', 'classes/table/', 'classes/user', 'pages/', 'templates/');
$fileName = $className . '.php';
foreach($locations AS $currentLocation)
{
if(file_exists($currentLocation . $fileName))
{
include_once ($currentLocation . $fileName);
return;
}
}
}
Now in my main class file I do have all of the necessary classes already included so that they won’t have to be searched for.
Here are my questions:
- Is this function efficient enough? Will there be a lot of load time or is there a way for me to minimize the load time?
- Is include_once() the way that I should go about including the classes?
- Is there a way that I could write the function to guess at the most popular folders? Or would that take up too much time and/or not possible?
- Would namespaces help me at all? (I am reading and learning about them right now.)
require, for two reasons: a) you don’t need to have PHP track if the file has been already included, because if it has it won’t need to call__autoloadin the first place and b) if the file cannot be included you won’t be able to continue execution anywayFor reference, the interaction between
__autoloadand namespaces is documented here.