Reputation: 6111
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 removed\server\service\product.php on line 2
Fatal error: require_once(): Failed opening required '../model/product.php' (include_path='C:\xampp\php\PEAR')
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?
Upvotes: 1
Views: 79
Reputation: 7703
Use include and require never without __DIR__. A relative path that starts with. or .. has the current directory as a base. The current working directory depends on various settings. __DIR__ is always the directory where the file itself is located.
For include the server/service/product.php from the file server/api/product/get.php you can do this:
require_once __DIR__."/../../service/product.php";
Upvotes: 0
Reputation: 807
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");
Upvotes: 1