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

\$\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/");
\$\endgroup\$
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.