I am working on my first MVC framework, and want to define 4 constants for BASE_PATH, APP_PATH, LIB_PATH & PUBLIC_PATH. My file structure looks like this:
/
/app
/controllers
/models
/views
/config
/db
/lib
/public_html
/css
/js
/img
My index.php file is located in the public_html directory. And currently has the following code:
error_reporting(E_ALL);
define('BASE_PATH',dirname(realpath(__FILE__)) . "/../");
define('APP_PATH',dirname(realpath(__FILE__)) . "/../app/");
define('LIB_PATH',dirname(realpath(__FILE__)) . "/../lib/");
define('PUBLIC_PATH',dirname(realpath(__FILE__)) . "/");
require LIB_PATH . 'core.php';
This works, but I feel like there must be a better way of doing it without all of the "..". Any suggestions or is this the best way of going about it? Let me know. Thank you!
ANSWER
Thank you to @fireeyedboy and @KingCrunch, I have come up with the solution I was looking for. This is my final code:
define('PUBLIC_PATH', dirname(__FILE__) . "/");
define('BASE_PATH', dirname(PUBLIC_PATH) . "/");
define('APP_PATH', BASE_PATH . "app/");
define('LIB_PATH', BASE_PATH . "lib/");
The realpath() function returns the absolute pathname. This function removes all symbolic links (like '/./', '/../' and extra '/') and returns the absolute pathname.
The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file.
If you are using PHP 7.0 and above then the best way to navigate from your current directory or file path is to use dirname(). This function will return the parent directory of whatever path we pass to it.
Using os.path.dirname() to get parent of current directory path.
How about this:
define('PUBLIC_PATH',dirname(realpath(__FILE__)) . "/");
define('BASE_PATH',dirname(PUBLIC_PATH));
define('APP_PATH',BASE_PATH . "/app/");
define('LIB_PATH',BASE_PATH . "/lib/");
In other words use dirname()
again. And re-order defining the constants to make direct use of them. Not sure it helps readability though.
First:
realpath(__FILE__)
is just useless
However, there no "real" better way, because ../
is not "dirty". The only other solution, that comes in my mind
dirname(dirname(__FILE__))
..
is the way a filesystem (its not invented by php ;)) defines its parent directory, just as well .
defines the current directory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With