Switch-based URL routing in PHP

非 Y 不嫁゛ 提交于 2021-02-07 10:04:09

问题


What I'm currently doing is this:

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.

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;
} 

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?


回答1:


You shouldn’t use switch like this.

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';
}



回答2:


The wrong part would be the switch case . As a better practice i would suggest you store all regex into an array and test it with that . It would be easyer to save the routes to a config file , or an ini file or database or xml or whatever will make you're life easyer in to long run ( if you need to edit/add/delete new routes ) .

In the second part you could use parse_url php function instead of regex witch will speed you're script a bit .



来源:https://stackoverflow.com/questions/4595624/switch-based-url-routing-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!