在PHP mvc中路由URL的最有效方法?

时间:2012-06-19 15:59:27

标签: php model-view-controller oop .htaccess

我正在开发一个简单的 php mvc,它可以做到最低限度但是我也需要它工作,这是我第一次使用mvc方法而不是prodcedural所以我正在学习去.. ..

在开发过程中,我偶然以一种奇怪的风格创建它,目前主要.htaccess包含几乎所有的物理重写,例如论坛是:

RewriteRule ^forum/([a-zA-Z0-9_]+)_([0-9]+)/$                    index.php?controller=forum&method=showThread&urlTitle=$1&threadId=$2 [L] 
RewriteRule ^forum/([a-zA-Z0-9_]+)_([0-9]+)/all/([0-9]+)$        index.php?controller=forum&action=showThread&urlTitle=$1&threadId=$2&page=$3 [L]

目前的工作方式是将所有网址定向到index.php,然后使用以下网址从网址中使用哪个控制器和方法:

的index.php

$actionName = $_GET['action'];
$controllerName = ucfirst(strtolower($_GET['type'])).'controller';

$controller = new $controllerName;
$controller->$actionName();

控制器/ forumcontroller.php

class forumcontroller{

    function showThread() {

        $thread = new Thread($_GET['threadId'], $_GET['uriTitle']); 
        require "templates/thread.php";
    }

但这意味着用户可以访问我不希望他们访问的位置,例如:

/public_html/templates/index.php

我认为我需要什么?

我认为主要的.htaccess看起来应该是这样的吗?

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]

然后在index.php中你会使用类似的东西:

$url = explode("/", `$_SERVER['QUERY_STRING']);`

$controller = $url[0];   //Returns "forum"
$data = $url[1];         //Returns the forum title and id

但是使用这种方法我不明白你如何用数据调用控制器内的动作?

你不必做类似的事情:

 if(!$data)
     $controller->loadForum();
 elseif($data)
     $controller->loadForumThread($data);

结论

我只是不理解如何最好地为具有许多不同格式的seo友好网址的网站进行路由,我理解mvc应该如何工作但我正在努力掌握路由部分和所有我遇到的例子看起来非常复杂!

我真的很难看到如何编码.htaccess和控制器以处理不同格式的大量网址,如下所示:

domain.com
domain.com/uploads
domain.com/profiles/username
domain.com/messages/inbox
domain.com/messages/createnew/userId
domain.com/forum/all/2
domain.com/forum/title_1/
domain.com/forum/title_1/all/3

1 个答案:

答案 0 :(得分:3)

这是一种类似于第二个.htaccess示例的方法。

$request = explode('/', substr($_SERVER['REQUEST_URI'], 1));
// Clean request array of empty elements
foreach($request as $k => $v)
    // Clear any empty elements
    if(!$v) unset($request[$k]);
$request = array_values($request);  // Renumber array keys

这给出了一个数字索引数组,表示请求的URI。应用程序可以假设请求中的第一个值是控制器的名称:

if(count($this->request) == 0) 
    $request[] = 'DefaultController';  // Responsible for homepage
$this->controller = new $request[0]( $request );

我还将$context变量传递给控制器​​构造函数,但是这个问题的范围超出了它(它负责数据库连接,当前用户数据和会话数据)。

之后,它只是发送请求:$this->controller->dispatch()

在调度方法内部,控制器本身知道请求数组。例如,在您的URL列表中,让我们看一下第三个示例:domain.com/profiles/username

控制器将被命名为“个人资料”:

class Profiles {
    private $request, $context;
    public function __construct($request, $context) {
        $this->request = $request;
        $this->context = $context;
    }

    public function dispatch() {
        if(count($this->request) == 2 && $this->request[1] == 'username') {
            // Load data from model for the requested username ($this->request[1])

            // Show View
        }
    }
}

有更好的方法可以将请求向量映射到操作,但希望你能得到这个数据。