My previous question broght up some discussion which suggested that I am wrong to use the likes of
require_once($_SERVER['DOCUMENT_ROOT'] . '/proj/database/database-common.php');
and should, instead be using
require_once(dirname(__FILE__) . '/database/database-common.php');
BUT, I have a multi-level hierarchy and some common functionality (dataebase, error handling, etc) which can be called from any level – how do I handlt that? E.g, my error handling requires a CSS file from $_SERVER[‘DOCUMENT_ROOT’]\css\my.css
If I do not have $_SERVER['DOCUMENT_ROOT'] as an anchor point, can I use something else? If not, how do I handle that a common file may wish to include another, but does not know from which level it itself is being included?
E.g.:
root
`- databse
`- validation
If validation/common.php wants to include database/database_common.php thhen, without an anchor, validation/common.php cannot know the path to database_common.php It is not ..\database/database_common.php if validation/common.php was incldued from a file in the root directory (and this is a simplified example)
My philiosophy is to always require a file in the file which uses it, so I can’t just include everthing in the root directory files ….
Can someoen clarify best pracise on this for me? Thanks
You could use a bootstrap file which is used across all others file and define all global parameters there, something like
and the require this master file in every file which needs to include other files so your following requires will become
This will solve in part your problem, but keeps thing consistent, the only part which change is the first require, but you can use relative paths to keeps code portable.
I’d not use
include_pathchanges because it will slow path resolution because php will search through all directories in the include path andstatis one of the most expensive syscall. Example: if you you have this include path.:/dir1:/dir2:/dir3and you require a file namedfoo.phpwhich is indir3php will make the following four stat calls:For this reason you should always use absolute paths when requiring files and should keep the include path limited to one or two paths.
Alternatively, if you’re using OOP you can always use autoloading for your classes which remove the need for requiring files and works pretty well. A good example of this technique is given in Zend Framework autoloader