我正在考虑使用以下两个选项之一来路由我的请求:
选项 1:使用 Mod-Rewrite 和漏斗编写的简单捕获路由 $_GET
路由到 index.php 以加载...
#default routing
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^blog/([0-9]+)?$ index.php?rt=blog¶ms=$1 [L,QSA]
// ..more custom routes, and then a default route
RewriteRule ^([A-Za-z]+)/([A-Za-z]+)/(.*)?$ index.php?rt=$1/$2¶ms=$3 [L,QSA]
选项 2:简单地将请求路由到 Front Controller,并创建一个 PHP 路由类来处理路由...
#default routing
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?rt=$1 [L,QSA]
/* --- on front controller, process $_GET['rt'] --- */
归根结底,哪个会运行得更快、更容易保护并且更容易维护?
还有其他想法吗?
注意:我没有运行已知的框架。我正在构建自己的 MVC 模式来学习它。
最佳答案
通常在 MVC 框架中,这种事情通常最好由前端 Controller (名为 index.php
或类似名称)处理。您使用 mod_rewrite 然后从所有 URL 中隐藏 index.php
,以便您的用户看到漂亮干净的路径。
它在 PHP 中也比在 Apache 的重写指令中更容易处理。 PHP 更灵活,更易于编写/理解。现在我想起来了,我不确定我是否见过 mod_rewrite 被用作任何 Web 框架的唯一路由引擎。
您的第二段代码是实现重写指令的方法。
关于php - Mod-Rewrite 还是 PHP 路由器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1868154/