-3

在工作 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" 

*/
4

1 回答 1

-1

基本方法似乎还可以,但是我需要整理一些东西,包括更好的变量名和范围,以及使用更合适的循环。

此外,据我所知,您希望找到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”,因此示例现在反映了这一点。

于 2012-08-12T15:56:19.607 回答