Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class RouterException extends Exception {}
- class NotFound extends RouterException {}
- class Router {
- protected
- $_routes = array(),
- $_path;
- function __construct($routes = null, $path = null) {
- if (is_array($routes)) {
- foreach ($routes as $pattern => $handler) {
- $this->addRoute($pattern, $handler);
- }
- }
- $this->_path = $path;
- }
- function compileRoute($pattern) {
- $replacements = array(
- 'num' => '\d+',
- 'alphanum' => '\w+',
- 'id' => '[1-9]\d*',
- 'any' => '.*'
- );
- $pattern = '/^' . preg_quote($pattern, '/') . '$/';
- foreach ($replacements as $k => $v) {
- $pattern = str_replace("<$k>", $v, $pattern);
- }
- return $pattern;
- }
- function addRoute($pattern, $handler) {
- $pattern = $this->compileRoute($pattern);
- $this->_routes[$pattern] = $handler;
- }
- function serve($path = null) {
- $path = $path ? $path : $this->_path;
- if (!$path) {
- throw new RouterException('Need path');
- }
- foreach ($this->_routes as $pattern => $handler) {
- if (preg_match($pattern, $path, $matches)) {
- return call_user_func_array($handler, array_slice($matches, 1));
- }
- }
- throw new NotFound();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement