user11555230
user11555230

Reputation:

Is there some way to "figure out the application base dir" other than this?

I've made a PHP framework. To start it, you do:

require 'framework.php';
framework_start(__DIR__);

I'm trying to eliminate the __DIR__ part, if at all possible. It's telling the framework what the "base dir" for the application is. I can't think of any way to determine the "__DIR__" for the file that calls framework_start(), from within framework_start().

I can't help but feel annoyed that it can't just be:

require 'framework.php';
framework_start();

... and then framework_start(); somehow figures out the __DIR__ value on its own. But if I just reference __DIR__ from the PHP file that contains framework_start(), it will obviously return the wrong dir path.

Is this possible at all? If so, how?

Upvotes: 3

Views: 86

Answers (1)

Dharman
Dharman

Reputation: 33305

I would suggest the following. Define a constant at the top of framework.php file to be used in your framework instead of __DIR__:

$trace = debug_backtrace(false);
$levelsToGoUp = 0; // set to 1 if called from within the function 
if (array_key_exists($levelsToGoUp, $trace)) {
    define('PARENTFILE', dirname($trace[$levelsToGoUp]['file']));
} else {
    define('PARENTFILE', __DIR__);
}

If you called debug_backtrace() inside the function framework_start() you would need to look at the entry with key 1 in the array (the first is the function itself), which I would recommend.

Upvotes: 1

Related Questions