Ricky
Ricky

Reputation: 115

Switch-based URL routing in PHP

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?

Upvotes: 2

Views: 1825

Answers (2)

Poelinca Dorin
Poelinca Dorin

Reputation: 9703

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 .

Upvotes: 0

Gumbo
Gumbo

Reputation: 655309

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

Upvotes: 4

Related Questions