Efficient autoload function
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/tabl开发者_开发知识库e/', '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.)
- This is answered very well here: autoload and multiple directories
- You should probably go with
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__autoload
in the first place and b) if the file cannot be included you won't be able to continue execution anyway - The answer for point 1 covers this
- Not necessarily; you need some namespace-like mechanism to implement faster loading (to only look where you have to) but you can fake it if necessary without using real namespaces
For reference, the interaction between __autoload
and namespaces is documented here.
精彩评论