脚本宝典收集整理的这篇文章主要介绍了在PHP mvc中路由URL的最有效方法?,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
在开发过程中我偶然以一种奇怪的方式创建它,目前主要的.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
$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.
以上是脚本宝典为你收集整理的在PHP mvc中路由URL的最有效方法?全部内容,希望文章能够帮你解决在PHP mvc中路由URL的最有效方法?所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。