2

I have been working on a fancy router/dispatcher class for weeks now trying to decide how I wanted it, I got it perfect IMO except performance is not what I am wanting from it. It uses a route map arrap = /forums/viewthread/:id/:page => 'forums/viewthread/(?\d+)' and loops through my map array with regex to get a match, I am trying to get something better on a high traffic site, here is a start...

$uri = "forum/viewforum/id-522/page-3";

$parts = explode("/", $uri);
$controller = $parts['0'];
$method = $parts['1'];
if($parts['2'] != ''){
    $idNumber = $parts['2'];
}

if($parts['3'] != ''){
    $pageNumber = $parts['3'];
}

Where I need help is sometime an id and a page will not be present sometime one or the other and sometimes both, so obvioulsy my above code would not cover that, it assumes array item 2 is always the id and 3 is always the page, could someone show me a practical way of matchting up the page and id to a variable only if they exist in the URI and without using regular expressions?

You can see what I have so far on my regular expressions versions in this question Is this a good way to match URI to class/method in PHP for MVC

Community
  • 1
  • 1
JasonDavis
  • 48,204
  • 100
  • 318
  • 537
  • 2
    You're trying to solve issues you haven't even experienced yet. Why do you think the router will be a bottleneck in a project? Why not database? – zerkms Aug 23 '11 at 00:57

2 Answers2

1
if ( ! empty($parts['2']))
{
    if (strpos($parts['2'], 'id-') !== FALSE)
    {
        $idNumber = str_replace('id-', '', $parts['2']);
    }
    elseif (strpos($parts['2'], 'page-') !== FALSE)
    {
        $pageNumber = str_replace('id-', '', $parts['2']);
    }
}

And do the same for $part[3]

Ibrahim AshShohail
  • 2,072
  • 14
  • 19
1

This seems more extendable:

$parts = explode("/", $uri);
$parts_count=count($parts);
//set default values
$page_info=array('id'=>0,'page'=>0);
for($i=2;$i<$parts_count;$i++) {
    if(strpos($parts[$i],'-')!==FALSE) {
        list($info_type,$info_val)=explode('-',$parts[$i],2);
        if(isset($page_info[$info_type])) {
            $page_info[$info_type]=(int)$info_val;
        }
    }
}

then just use $page_info values. You can easily add other values this way and more levels of '/'.

XzKto
  • 2,472
  • 18
  • 18
  • That is awsome, and very nice that I could add other things in the future thanks – JasonDavis Aug 23 '11 at 16:29
  • Glad that I could help. Btw, I forgot to place count() outside of the loop(to increase performance a bit) - updated my post. – XzKto Aug 24 '11 at 07:22