I've recently helped fellow SOFer to answer his question here: Routing in my PHP MVC framework
Then I thought
Hey, why not improve this code and put in my snippets library.
This is what I came up with:
/**
* @author Gajus Kuizinas <[email protected]>
* @copyright Anuary Ltd, http://anuary.com
* @version 1.0.3 (2011 12 07)
* @param array $routes e.g., array('page/:id' => array('controller' => 'page', 'parameters' => array('id' => 1)));
*/
function ay_dispatcher($url, $routes)
{
$url = array
(
'original' => $url,
'path' => explode('/', parse_url($url, PHP_URL_PATH))
);
$url['length'] = count($url['path']);
foreach($routes as $filter => $data)
{
// reset the parameters every time in case there is partial match
$parameters = array();
$filter = array
(
'original' => $filter,
'path' => explode('/', $filter)
);
$filter['length'] = count($filter['path']);
// this filter is irrelevent
if($url['length'] <> $filter['length'])
{
continue;
}
foreach($filter['path'] as $i => $key)
{
if(strpos($key, ':') === 0)
{
$parameters[substr($key, 1)] = $url['path'][$i];
}
// this filter is irrelevent
else if($key != $url['path'][$i])
{
continue 2;
}
}
if(!array_key_exists('parameters', $data))
{
$data['parameters'] = array();
}
$data['parameters'] = array_merge($data['parameters'], $parameters);
return $data;
}
return FALSE;
}
The 1.0.2 version https://gist.github.com/68bcb1e087237bde76ea.
I'd like to hear comments on the code logic. It is most certainly better in terms of performance than any regex dispatcher. Did I forget any essential features, though?