In PHP when we include or require some file using some initializers like the following. How can we overcome filepath issues which occurs if you include the same initializer in a sub-directory or different location.
<?php
// settings
$settings = array('config');
foreach ($settings as $setting) {
require_once "../system/settings/{$setting}.php";
}
// neutrals
$neutrals = array('functions');
foreach ($neutrals as $neutral) {
require_once "../system/neutrals/{$neutral}.php";
}
// helpers
$helpers = array('database', 'file', 'logger', 'user', 'session', 'database');
foreach ($helpers as $helper) {
require_once "../system/helpers/{$helper}.php";
}
// models
$models = array('test');
foreach ($models as $model) {
require_once "../system/models/{$model}.php";
}
?>
Above script is in a file all_initializer.php. The hurdle here is that i cant use the same initializer in a public sub-directory or other location as it will occur fatal errors (if its a required file) of file not found.
EDIT
For e.g. I am using this initialzer in a public folder in a index.php file then there’s a sub-directory in the public folder public/sub. How can I use the same initializer in public/sub/index.php as I used in public/index.php ?
You could use the
file_existsto avoid fatal errorsAs for the path issues you are referring to, you can include this file from anywhere so long as you supply the proper base path for your operations. Defining a
ROOT_PATHin yourindex.phpfile would help you detect where your script is and what it needs to load.So for instance if you have this structure:
in your
index.phpyou can define aROOT_PATHconstant that will be used throughout the application and serve as a point of reference.You can also have a constant just for your system folder
and then all your
require_oncedeclarations become:EDIT: Based on additional information in the question
In index.php you define
and then:
to do your initialization. The same thing happens in the
public/sub/index_sub.php.Your
all_includes.phpbecomes: