Advertisement
stuppid_bot

Untitled

May 29th, 2014
356
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.42 KB | None | 0 0
  1. <?php
  2.  
  3. class RouterException extends Exception {}
  4.  
  5. class NotFound extends RouterException {}
  6.  
  7. class Router {
  8.     protected
  9.         $_routes = array(),
  10.         $_path;
  11.  
  12.     function __construct($routes = null, $path = null) {
  13.         if (is_array($routes)) {
  14.             foreach ($routes as $pattern => $handler) {
  15.                 $this->addRoute($pattern, $handler);
  16.             }
  17.         }
  18.         $this->_path = $path;
  19.     }
  20.  
  21.     function compileRoute($pattern) {
  22.         $replacements = array(
  23.             'num' => '\d+',
  24.             'alphanum' => '\w+',
  25.             'id' => '[1-9]\d*',
  26.             'any' => '.*'
  27.         );
  28.         $pattern = '/^' . preg_quote($pattern, '/') . '$/';
  29.         foreach ($replacements as $k => $v) {
  30.             $pattern = str_replace("<$k>", $v, $pattern);
  31.         }
  32.         return $pattern;
  33.     }
  34.  
  35.     function addRoute($pattern, $handler) {
  36.         $pattern = $this->compileRoute($pattern);
  37.         $this->_routes[$pattern] = $handler;
  38.     }
  39.  
  40.     function serve($path = null) {
  41.         $path = $path ? $path : $this->_path;
  42.         if (!$path) {
  43.             throw new RouterException('Need path');
  44.         }
  45.         foreach ($this->_routes as $pattern => $handler) {
  46.             if (preg_match($pattern, $path, $matches)) {
  47.                 return call_user_func_array($handler, array_slice($matches, 1));
  48.             }
  49.         }
  50.         throw new NotFound();
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement