2
\$\begingroup\$

I'm writing a php library for managing configurations of an application.

but the problem is anyone who uses my library will store their configuration files in ./config folder of their project root directory.

e.g. var/www/example.com/config/site.php

and my library is installed in a sub directory of the project

i.e vendor/azi/config/src/Config.php

To Load files from project root i am doing it this way

 if (!defined('PATH_TO_CONFIG_DIR')) {
 define('PATH_TO_CONFIG_DIR', dirname(dirname(dirname(dirname(dirname(__FILE__))))) . "/config/");
 }

is it right ? Or It can be more efficient. Code suggestion will be helpful.

Github : https://github.com/azeemhassni/Config

asked Nov 28, 2015 at 9:52
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

Instead of nesting the dirname calls, according to the documentation for dirname you could call this as of PHP 7:

dirname(__FILE__, 5)

For supporting lower versions of PHP, you could write a parentDirectory function:

function parentDirectory($path, $levels) {
 for ($i = 0; $i < $levels; $i++) {
 $path = dirname($path);
 }
 return $path;
}

Or just embed it inside your current code, without a specific function:

$configPath = __FILE__;
for ($i = 0; $i < 5; $i++) {
 $configPath = dirname($configPath);
}
define('PATH_TO_CONFIG_DIR', $configPath . "/config/");
answered Nov 28, 2015 at 11:38
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.