stuppid_bot

PHP Router Class v.0.2

Jun 27th, 2013
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.60 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 add($method, $rule, $func) {
  12.         array_push($this->_routes, $method, $rule, $func);
  13.     }
  14.  
  15.     public function get($rule, $func) {
  16.         array_push($this->_routes, 'GET', $rule, $func);
  17.     }
  18.  
  19.     public function post($rule, $func) {
  20.         array_push($this->_routes, 'POST', $rule, $func);
  21.     }
  22.  
  23.     public function put($rule, $func) {
  24.         array_push($this->_routes, 'PUT', $rule, $func);
  25.     }
  26.  
  27.     public function delete($rule, $func) {
  28.         array_push($this->_routes, 'DELETE', $rule, $func);
  29.     }
  30.  
  31.     public function process() {
  32.         $n = count($this->_routes);
  33.         for ($i = 0; $i < $n; $i += 3) {
  34.             $method = $this->_routes[$i];
  35.             if (strtoupper($method) == $_SERVER['REQUEST_METHOD']) {
  36.                 $rule = $this->_routes[$i + 1];
  37.                 $func = $this->_routes[$i + 2];
  38.                 @$is_regexp = preg_match($rule, '') !== false;
  39.                 if ($is_regexp) {
  40.                     if (preg_match($rule, $this->_url, $matches)) {
  41.                         return call_user_func_array($func, array_slice($matches, 1));
  42.                     }
  43.                 }
  44.                 else if ($rule == $this->_url) {
  45.                     return call_user_func($func);
  46.                 }
  47.             }
  48.         }
  49.         if ($this->defaultRoute) {
  50.             $func = $this->defaultRoute;
  51.             call_user_func($func);
  52.         }
  53.     }
  54. }
  55.  
  56. ?>
Advertisement
Add Comment
Please, Sign In to add comment