Dynadot Aftermarket: discover domain gems worth investing in. Visit our aftermarket.

Better code for router/dispatcher

SpaceshipSpaceship
SpaceshipSpaceship
Namecheap AuctionsNamecheap Auctions
Watch

SGBoise

Established Member
Impact
1
Hello,

I am trying to implement router/dispatcher for my script. I looked at how phpcake, codeigniter and zend framework work but they were way to complicated to what I needed.

I found a tutorial at http://www.phpaddiction.com/tags/axial/url-routing-with-php-part-one/ which is simple to implement.

I have two types of uri:

category / id / description.html
or
category / subcategory / id / description.html

Example: /videos/funny/234/funny_monkey_dancing.html


What I am trying to do is determine category and subcategory, if there is a subcategory, and then the ID.

The way I am doing it right now doesn't look like the proper way. Is there a better way to do this?


Here is my code from the tutorial with a few modifications.

PHP:
//$requestURI = explode('/', $_SERVER['REQUEST_URI']);
$requestURI = explode('/', "tms_routing/videos/funny/234/funny_monkey_dancing.html");
$subfolder = "tms_routing";

// Remove the subfolder
if (!$subfolder == "") {
	for($i= 0;$i < sizeof($requestURI);$i++){
		if ($requestURI[$i] == $subfolder){
			unset($requestURI[$i]);
			break;
		}
	}
}

// Map paths
if (is_numeric($requestURI[3])) {
	$array["category"] = $requestURI[1];
	$array["subcategory"] = $requestURI[2];
	$array["id"] = $requestURI[3];
} else {
	$array["category"] = $requestURI[1];
	$array["id"] = 	$requestURI[2];
}
 
0
Close
The views expressed on this page by users and staff are their own, not those of NamePros.
GoDaddyGoDaddy
I don't think you need to "remove the subfolder."

This line:
PHP:
$array["category"] = $requestURI[1];
is the same in both blocks of your second "if" statement.

I'm assuming that any part of the request URI array that is == to $subfolder would be at 0, right?

If so, just check to see if the [0]th element == $subfolder. If so, increment an $i by one:

PHP:
$i = 0;
if ($requestURI[0] == $subfolder) $i ++;

// Map paths
$array["category"] = $requestURI[$i];

if (is_numeric($requestURI[$i+2])) {
    $array["subcategory"] = $requestURI[$i+1];
    $array["id"] = $requestURI[$+2];
} else {
    $array["id"] = $requestURI[$i+1];
}

I *think* that'll work. Did you want to assign the name of the html file (the last element of $requestURI) to the array, too?

PS. Just to be clear, using my method (or even if not), you can remove the whole "Remove the subfolder" if block.
 
Last edited:
0
Close
AIVikingsAIVikings

We're social

Escrow.com
Spaceship
Domain Recover
CryptoExchange.com

NamePros updates

Search: choose where to search from the All tab
Open the search at the top of any page. On the All tab, the list next to the search box lets you choose where to search: everything, all...
AIVikings
Catchy
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back