I have the following file structure in my project:
+ server + api + product - get.php + database - product.php + model - product.php + service - product.php + utilities - controller.php - database.php
Then in my server/api/product/get.php
I have the following lines:
require_once("../../service/product.php"); require_once("../../utilities/controller.php");
I believe this is properly loading the service because when I use Insomnia to hit the endpoint I am getting this error in the server/api/service/product.php
file:
Warning: require_once(../model/product.php): failed to open stream: No such file or directory in C:full path removedserverserviceproduct.php on line 2
Fatal error: require_once(): Failed opening required ‘../model/product.php’ (include_path=’C:xamppphpPEAR’)
In my server/service/product.php
file I have the following:
require_once("../model/product.php"); require_once("../database/product.php");
And it is failing on the first require_once
.
So my question to y’all is why would the relative path in my controller layer work, but the relative path in the service layer fail?
Advertisement
Answer
You could as an alternative use the __DIR__
magic constant as per the documentation the constant gives: ‘The directory of the file. If used inside an include, the directory of the included file is returned’. Which reduces the likelihood of errors through relative pathing.
Example:
require_once(__DIR__ . "/../../service/product.php");