Ibu
Ibu

Reputation: 43850

loading only needed files or all the framework?

I have looked around stackoverflow and i still can't find an answer to my question.

I am using my custom framework for a website and as of right now, i use an include in my index that php to load all the classes the framework uses.

But for my database objects i use a little script to include all the files, because there are many layers of class for each table. (each table has at least 4 files)

Here is the snippet i currently use to load them.

// the constants are the directories to look for files
$__dirs = array(CORE_PATH,CX_SETTINGS,BASE_MODEL,MODEL,CUSTOM_MODEL,CONTROLLER,PLUG_IN,HELPER_FUNCTIONS);
$__accepted_ext = '.php';
foreach ($__dirs as $dir) {
    if ($handle = opendir($dir)) {
        // peer files first
        while (false !== ($file = readdir($handle))) {
            if ((strpos($file,$__accepted_ext) !== false)){
                require_once($dir.DS.$file);
                //echo "$dir : $file : works \n"; // debug
            }
        }
        closedir($handle);
    }
}

This method will scan every directory i provide and include all my php files.

My problem is that this load every single file of my framework, regardless i use them or not. So i assume this is not the best way to handle it, and that i might be creating unnecessary overhead.

Now I read about the __autoload() function and i consider it my alternative. But is this something i should even be worried about (including even files i won't use)? What are the methods currently being used to handle this problem?

EDIT:

NOTE: all the files included are classes, not files included by mistake. example: I might load the comment class, which is valid, but not used in all my pages. so it's in some way unnecessary

Upvotes: 0

Views: 100

Answers (2)

Timur
Timur

Reputation: 6718

If you are trying to avoid unnecessary files with classes definition, spl_autoload_register() or __autoload() will be the best way. If you registering autoload function, it will be called automatically when you are trying to instantiate undefined class. One problem you might face is how to handle directories structure with subdirectories with classes etc. In can be solved easily. But, if all of your classes are in the same directory, you will not face any problems.

Upvotes: 2

Andreas
Andreas

Reputation: 2678

Why don't you try to make a structure of directories or use different endings for classes? Like '.cls.php'. That would reduce the overhead. If you want to do it automatically you only include this files. But as far as I know, you can't avoid loading unused classes ...

Upvotes: 0

Related Questions