Advertisement
Guest User

Untitled

a guest
Oct 28th, 2012
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3. class Router{
  4.  
  5.     private $default;
  6.     private $rule;
  7.     private $path;
  8.     private $baseInclusionPath;
  9.    
  10.     function Route( $default='more/404' ) {
  11.         $this->default = $default;
  12.         $this->baseInclusionPath = 'controllers/';
  13.        
  14.         //> $_SERVER['REQUEST_URI'] sample: /page/file?abc
  15.         $this->path = $_SERVER['REQUEST_URI'];
  16.         $this->path = substr($this->path,1);    //> Removing leading slash
  17.     }
  18.    
  19.     public function add( $pattern, $app = null ) {
  20.         $this->rule[$pattern] = $app;
  21.         return $this;
  22.     }
  23.    
  24.     public function dispatch() {
  25.        
  26.         foreach($this->rule as $pattern=>$app) {
  27.             if (preg_match('#^'.$pattern.'$#i',$this->path,$match)) {
  28.                 print_r($match);
  29.                 $this->run($app,$match);
  30.                
  31.                 return true;
  32.             }
  33.         }
  34.        
  35.         //> Nothing Matched run 404 error
  36.         $this->run($this->default);
  37.     }
  38.    
  39.     private function run($app,$match=array()) {
  40.    
  41.         //> First entry is all the string matched
  42.         array_shift($match);
  43.    
  44.         if ($app==null) {
  45.             $app = $match[0];
  46.         }
  47.        
  48.         require($this->baseInclusionPath.$app.'.php');
  49.        
  50.         //> Remove the controller name
  51.         array_shift($match);
  52.         $method = $match[0];
  53.        
  54.         //> Remove the method name
  55.         array_shift($match);
  56.        
  57.         $app = 'Controller'.ucfirst($app);
  58.         if (function_exists($app)) {
  59.             call_user_func_array($app,$match);
  60.         } else {
  61.             $app = new $app;
  62.             call_user_func_array(array($app, $method), $match);
  63.         }
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement