PHP 中基于交换机的 URL 路由 [英] Switch-based URL routing in PHP
问题描述
我目前正在做的是:
我有一个 $path
变量,它是 index.php/(我用 .htaccess 隐藏)之后的所有内容,直到一个问号以忽略查询字符串.
I have a $path
variable, which is everything after index.php/ (which I hide with .htaccess) up to a question mark to ignore the querystring.
然后我在该变量上使用带有 preg_match
情况的 switch
来确定它应该调用什么脚本.例如:
Then I use a switch
with preg_match
cases on that variable to determine what script it should call. For example:
switch (true)
{
case preg_match('{products/view/(?P<id>\d+)/?}', $path, $params):
require 'view_product.php';
break;
...
default:
require '404.php';
break;
}
这样我就可以只使用 $params['id']
访问产品 ID,如果需要,使用查询字符串进行过滤、分页等.
This way I can access the product id just using $params['id']
and, if needed, use the querystring for filtering, pagination, etc.
这种方法有什么问题吗?
Is there anything wrong with this approach?
推荐答案
你不应该像这样使用 switch
.
You shouldn’t use switch
like this.
最好使用数组和 foreach
像:
Better use an array and foreach
like:
$rules = array(
'{products/view/(?P<id>\d+)/?}' => 'view_product.php'
);
$found = false;
foreach ($rules as $pattern => $target) {
if (preg_match($pattenr, $path, $params)) {
require $target;
$found = true;
break;
}
}
if (!$found) {
require '404.php';
}
这篇关于PHP 中基于交换机的 URL 路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!