PHP Routing class that translates any valid PCRE into a closure, in 14 lines of wholesome goodness For the impatient:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class RegexRouter { private $routes = array(); public function route($pattern, $callback) { $this->routes[$pattern] = $callback; } public function execute($uri) { foreach ($this->routes as $pattern => $callback) { if (preg_match($pattern, $uri, $params) === 1) { array_shift($params); return call_user_func_array($callback, array_values($params)); } } } } |