Please consider the following folder structure:
webroot
|_config
| |_config.php
|_public
| |_MyMainEntryPoint.php
|_src
|_inc
| |_DatabaseProcedures.php
|_objects
| |_MyFancyObject.php
|_SomeComponentA.php
|_SomeOtherComponentB.php
Imagine, that config.php
contains the code to connect to the database, DatabaseProcedures.php
contains wrappers around the stored procedures in the database I want to use from my website and MyFancyObject.php
defines a class that wraps data returned by one of the stored procedures.
SomeComponentA.php
might be used by MyMainEntryPoint.php
, while I temporarily have placed SomeOtherComponentB.php
where i placed it to do some sneaky debugging. Both components use the MyFancyObject
and both need to access the database. (Naturally, the database procedures need to rely on config.php
)
I need to sprinkle a generous amount of require_once
into most of the files to resolve all names of functions and classes. The paths I had to specify had me scratching my head.
From here I gather, that the paths I need to give depend on the location of the main executing script. So in the case of directly browsing to SomeOtherComponentB.php
this would be the src
-Folder. So my links would be thus:
SomeOtherComponentB.php:
require_once "inc/DatabaseProcedures.php";
DatabaseProcedures.php:
require_once "../config/config.php";
require_once "objects/MyFancyObject.php"
While when directly browsing to MyMainEntryPoint.php
the links would be different:
MyMainEntryPoint.php:
require_once "../src/SomeComponentA.php";
SomeComponentA.php:
require_once "../src/inc/DatabaseProcedures.php";
DatabaseProcedures.php:
require_once "../config/config.php";
require_once "../src/objects/MyFancyObject.php";
Note the difference for the linking of MyFancyObject.php
. I have tested both versions and each on its own works as expected.
But seriously: How is this supposed to be a behaviour benefitting the mental health of the poor sod having to deal with it?
Is there a way to tell php: Always take paths relative to the file that does the requiring / including?