Based off simple controller implementations like those seen in micro-frameworks like Slim, Silex, F3, Laravel, Tonic, Flight, Klein, etc.
/EDIT tried to link the above sources, but as a new user I only get 2 links...
Any potential issues? Improvements?
class Router {
private static $routes = array();
private function __construct() {}
private function __clone() {}
public static function route($pattern, $callback) {
$pattern = '/' . str_replace('/', '\/', $pattern) . '/';
self::$routes[$pattern] = $callback;
}
public static function execute() {
$url = $_SERVER['REQUEST_URI'];
$base = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
if(strpos($url, $base) === 0) {
$url = substr($url, strlen($base));
}
foreach (self::$routes as $pattern => $callback) {
if(preg_match($pattern, $url)){
preg_match_all($pattern, $url, $matches);
array_shift($matches);
$params = array();
foreach($matches as $match){
if(array_key_exists(0, $match)){
$params[] = $match[0];
}
}
return call_user_func_array($callback, $params);
}
}
}
}
Takes a regexp and a callback, checks the URI for the first match... e.g.,
Router::route('blog/(\w+)/(\d+)', function($category, $id){
print $category . ':' . $id;
});
Router::execute();
// if url was http://example.com/blog/php/312 you'd get back "php:312"...
TYIA.