The routing components of today's frameworks can get fairly sophisticated, but if we boil it down to its simplest, identifying a route can be as simple as a set of if-statements. Here's an exmaple.
PHP Code:
<?php
function routingMatch($url)
{
// root url
if ('/' == $url) {
return array(
'controller' => 'Default',
'action' => 'index'
);
}
// blog urls
// /blog
// /blog/show/{id}
if ('/blog' == $url) {
return array(
'controller' => 'Blog',
'action' => 'index'
);
} elseif (preg_match('#^/blog/show/(\d+)$#', $url, $matches)) {
return array(
'controller' => 'Blog',
'action' => 'show',
'id' => $matches[1]
);
}
// generic urls
// /{controllername}
// /{controllername}/{method}/{paramname}
if (preg_match('#^/([^/]+)$#', $url, $matches)) {
return array(
'controller' => $matches[1],
'action' => 'index'
);
} elseif (preg_match('#^/([^/]+)/([^/]+)/([^/]+)$#', $url, $matches)) {
return array(
'controller' => $matches[1],
'action' => $matches[2],
'param' => $matches[3]
);
}
// if nothing else matches, then 404
return array(
'controller' => 'Error',
'action' => 'error404'
);
}
$routingParameters = routingMatch($_SERVER['REQUEST_URI']);
Bookmarks