开发者

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:

  1. 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?
  2. Is include_once() the way that I should go about including the classes?
  3. 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?
  4. Would namespaces help me at all? (I am reading and learning about them right now.)


  1. This is answered very well here: autoload and multiple directories
  2. 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
  3. The answer for point 1 covers this
  4. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜