Hello,

I’m a full stack developer and owner of Truecast that lives in Holley, Oregon, 
USA. 

Introduction

Navigating up multiple directory levels is a common requirement in PHP 
applications, especially when managing paths in complex projects. Currently, 
this is achieved by chaining calls to the dirname() function. This method, 
while functional, can become cumbersome and less readable with increasing 
directory depth.

Proposed Feature

I propose the introduction of a new function, upDir(), which simplifies the 
process of moving up multiple directory levels in a file path. This function 
extends the utility of the existing dirname() by allowing a user to specify the 
number of directory levels they wish to ascend in a single function call.

Function Prototype:

function upDir(int $levels = 1, string $path = __DIR__): string

Function Example:

function upDir(int $levels = 1, string $path = null) {
    if  ($path === null) 
                   $path = __DIR__;   

    for ($i = 0; $i < $levels; $i++)
        $path = dirname($path);
    
    return $path;
}

require upDir(4).'/init.php';
Parameters:

path: The input path.
levels: The number of parent directories to ascend.
Return:

Returns the path of the parent directory after ascending the specified levels.
Benefits

Improved Readability: Reduces the complexity and improves the readability of 
the code, making it easier to understand at a glance, especially when dealing 
with multiple nested directories.
Error Reduction: Decreases the likelihood of errors that can occur from 
multiple chained dirname() calls, like miscounting the number of calls needed.
Efficiency: Potentially increases efficiency by reducing the number of function 
calls in a script.
Potential Issues and Considerations

Backward Compatibility: The function would be an addition to the existing PHP 
functions and is not expected to affect backward compatibility.
Performance: Initial benchmarks would need to be conducted to compare its 
performance against repeated dirname() calls to ensure there are no significant 
overheads.
Naming and Parameters: Further discussion might be required to finalize the 
name of the function and whether additional parameters (such as handling 
symbolic links differently) might be necessary.
Open Questions

Should there be any specific behaviors or exceptions when the number of levels 
exceeds the current depth of the path?
Is there a significant demand or use case from the community that justifies the 
inclusion of this function in the core PHP library?
I look forward to feedback from the community to refine this proposal and gauge 
interest in moving forward with an RFC.



Thanks!

Daniel Baldwin
Truecast
https://www.truecastdesign.com
458-266-8064






Attachment: smime.p7s
Description: S/MIME cryptographic signature

Reply via email to