For a couple of years I have been working on my own lightweight MVC framework for PHP. Which I may at some point release under an opensource license.
Here is what I have been using for handling routes:
function routes($routes, $uriPath) {
// Loop through every route and compare it with the URI
foreach ($routes as $route => $actualPage) {
// Create a route with all identifiers replaced with ([^/]+) regex syntax
// E.g. $route_regex = shop-please/([^/]+)/moo (originally shop-please/:some_identifier/moo)
$route_regex = preg_replace('@:[^/]+@', '([^/]+)', $route);
// Check if URI path matches regex pattern, if so create an array of values from the URI
if(!preg_match('@' . $route_regex . '@', $uriPath, $matches)) continue;
// Create an array of identifiers from the route
preg_match('@' . $route_regex . '@', $route, $identifiers);
// Combine the identifiers with the values
$this->request->__get = array_combine($identifiers, $matches);
array_shift($this->request->__get);
return $actualPage;
}
// We didn't find a route match
return false;
}
$routes is a passed array formatted like this:
$routes = array(
// route => actual page
'page/:action/:id' => 'actualPage',
'page/:action' => 'actualPage',
)
$uriPath is the URI path without a leading forward-slash e.g. page/update/102
In my page controllers I can access the the route information like so:
echo $this->request->__get['action'];
// update
echo $this->request->__get['id'];
// 102
My question is essentially "can this be simplified or optimised?". With particular emphasis on simplifying the regex and the number of preg_replace and preg_match calls.