在PHP mvc中路由URL的最有效方法?
我正在开发一个简单的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 解决方法
这是一种类似于第二个.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 } } } 有更好的方法可以将请求向量映射到操作,但希望你得到了这个jist. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |