I've just started working on a larger preexisting code base (PHP) and it has come to my attention that a lot of these files use includes/requires in an unreadable way. The includes/requires sort of cascade through the file system, because almost every file in the system includes/requires a file called common.php. This common file includes/requires just about every other file, so it seems that when a developer was in doubt, they just included/required common and called it good.
This was written by professional web developers, and I'm still a student, so I'm curious if this is common practice in PHP. In PHP should there be a common file that includes/requires everything, should each file be included/required case by case, or is there a different way that is common practice?
On a side note: I'm trying to switch out an api file for a new one (while keeping the old for compatibility testing), and it is difficult for me to tell which files use my new api or the old one.
Generally, includes should be used for view based material (HTML, Smarty, perhaps XML or XSLT) as in mark up used to construct a view in an MVC approach. However, require();
or require_once();
are used to control the incorporation of server side core functionality in a functional or object oriented setting (Controllers and Models in MVC).
Both require();
or require_once();
provide a programmatic safety mechanism where if the code fails, the code stops running and errors are sent to the logs - See documentation for require and require_once. Where as include();
will continue to run erroneous code despite errors - you do not want that.
To your other question concerning one file that "includes everything", some PHP frameworks like Zend and CodeIgniter allow for something called an auto loader - this loads all the available classes and instantiates the main core classes for the programmer to use objects at will.
If you are not using a framework, you can somewhat simulate this by creating a config or in your case a common file. However, you may not want to just arbitrarily load everything, as it could create confusion when other developers are trying to troubleshoot later - as you might be finding out now. You will have to evaluate, test and re-architect your code to figure out what is really common and what is sparsely used throughout your code. I have done this in the past by tracing - adding error_log()
and var_dump()
in an effort to follow the data as it moves through the code.