I’ve inherited a Class-based PHP site where every page of the site is its own Class. The index.php handles what page you view based on the p parameter, and then calls that specific Class. For example, the search page of the site is simply mysite.com/?p=search
One of the first lines in the index.php calls an Autoload.php file which does an include of every single Class-based page of the site. This means that no matter which page you are on, the script is loading every single other page/class.
My questions:
- There is NO connection between those pages/classes, so is it really necessary to load all of them on every pageload?
- Does it slow down the script having to
includeover 50 pages/classes on every pageload or is it negligible? - If so, then shouldn’t I do an if-based check to determine which page/class I should load based on the
pparameter and ONLY load that one rather than load every page on every pageload? - Or is there some other potential downside of doing that that I’m not aware of?
That’s a confusing name for the file, as autoloading is a mechanism in PHP that allows you to load classes as and when they are needed, a good solution when you have many classes and only a few will be needed for each execution.
For example:
So, to answer your questions:
It is not necessary to load them all, however classes that are used must be available, either by loading them all together (current situation), loading them conditionally (
if(p == 'whatever') require 'classes/whatever.php'), or by using autoloading.There is some delay whenever a file is included as the file must be parsed/executed. PHP is fairly fast but still, including files you do not need is a waste. If you’re using bytecode caching, the retrieved bytecode must still be executed.
That is one avenue of improvement, autoloading presents a more dynamic alternative.
Dependencies may be a problem if any of your page classes depend on another class, as your conditional loading could get very bloated.
Also a little additional material regarding bytecode caching, if you’re using it:
The summary seems to be that, as long as you use
includeorrequireto load the file, bytecode caching will work as intended.