stuppid_bot

PHP Router Class

Jun 26th, 2013
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.29 KB | None | 0 0
  1. <?php
  2.  
  3. class Router {
  4.     public $defaultRoute;
  5.     protected $url, $routes = array();
  6.  
  7.     public function __construct($url) {
  8.         $this->url = $url;
  9.     }
  10.  
  11.     public function dispatch($method, $url, $func) {
  12.         array_push($this->routes, $method, 0, $url, $func);
  13.     }
  14.  
  15.     public function match($method, $regexp, $func) {
  16.         array_push($this->routes, $method, 1, $regexp, $func);
  17.     }
  18.  
  19.     public function run() {
  20.         $count = count($this->routes);
  21.         for ($i = 0; $i < $count; $i += 4) {
  22.             if (strtoupper($this->routes[$i]) == $_SERVER['REQUEST_METHOD']) {
  23.                 if ($this->routes[$i + 1]) {
  24.                      if (preg_match($this->routes[$i + 2], $this->url,
  25.                              $matches)) {
  26.                          $func = $this->routes[$i + 3];
  27.                          return call_user_func_array($func,
  28.                                  array_slice($matches, 1));
  29.                      }
  30.                 }
  31.                 else if ($this->routes[$i + 2] == $this->url) {
  32.                     $func = $this->routes[$i + 3];
  33.                     return $func();
  34.                 }
  35.             }
  36.         }
  37.         if ($this->defaultRoute) {
  38.             $func = $this->defaultRoute;
  39.             $func();
  40.         }
  41.     }
  42. }
  43.  
  44. ?>
Advertisement
Add Comment
Please, Sign In to add comment