在调用控制器文件夹中包含文件的更好方法(根控制器具有文件夹)


Better way for including file in calling controller folder (root controller has folders)

在工作的PHP MVC上,在CONTROLLER文件夹上,我有一个文件控制器,但里面有文件夹,必须在文件夹内称为控制器。

没有人有更好的方法和很好的代码实现这些?

我正在以这种方式工作,但我不确定这是调用控制器的最佳方式吗?

/*
STRUCTURE OF DIR FILES: controllers:
a/b/c/file.php
a/b/c <-- IS DIRECTORY
a/b/c <-- IS FILE
*/
$uri_result = false;
$controller_called = false;
/* called controllers */
$uri_segments[0] = 'a';
$uri_segments[1] = 'b';
$uri_segments[2] = 'c';
#$uri_segments[3] = 'file.php';
/* end called controllers */
$counted = count($uri_segments);
$filled = array();
$i = 0;
do {
    if ($i < $counted)
    {
        $z[] = $uri_segments[$i];
        $ez = implode('/', $z);
    }
    if (file_exists($ez))
    {
        $uri_result = $ez;
        $controller_called = $z[$i];    
    }
++$i;
} while ($i < $counted);
var_dump($uri_result,$controller_called);
/* RESULTS:
If called $uri_segments[0] to uri_segments[3]
string(14) "a/b/c/file.php" string(8) "file.php" 
If called $uri_segments[0] to uri_segments[2]
string(5) "a/b/c" string(1) "c" 
*/

基本方法似乎没问题,但有一些事情我会整理,包括更好的变量名称和范围,以及使用更合适的循环。

此外,从我所看到的,您希望找到 URL 路径的最长部分来充当控制器,因此可能希望从长开始并变得更短,而不是从短开始并变长。

/**
 * Find the most specific controller file to serve a particular URL path
 *
 * @param string $url_path Relative path passed through from URL handler
 * @return string $controller_file Relative path to controller file
 */
function find_controller_file($url_path)
{
    $url_parts = explode('/', $url_path);
    // Start with the full path, and remove sections until we find a controller file
    while ( count($url_parts) > 0 )
    {
        // Concatenate remaining parts of path; this will get shorter on each loop
        $test_path = implode('/', $url_parts) . '.php';
        if ( file_exists($test_path) )
        {
            // We've found a controller! Look no further!
            return $test_path;
        }
        else
        {
            // No controller there. Let's remove the last path part and try again
            array_pop($url_parts);
        }
    }
    // If we reach here, we never found a controller. This is probably an error.
    throw new Controller_Not_Found_Exception();
}

编辑(接受后) 根据 hakra 下面的评论,要包含的文件可能总是具有扩展名".php",因此示例现在反映了这一点。