View difference between Paste ID: 9F02GEyN and FJhgyheh
SHOW: | | - or go back to the newest paste.
1
<?php
2
3
class Router{
4
 
5
    private $default;
6
    private $rule;
7
    private $path;
8
    private $baseInclusionPath;
9
       
10-
        function __construct( $default='more/404' ) {
10+
        function __construct( $default='more/404', $path = null ) {
11
                $this->default = $default;
12
                $this->baseInclusionPath = 'controllers/';
13
               
14
                //> $_SERVER['REQUEST_URI'] sample: /page/file?abc
15-
                $this->path = $_SERVER['REQUEST_URI'];
15+
                if ($path == null) {
16-
                $this->path = substr($this->path,1);    //> Removing leading slash
16+
                   $this->path = $_SERVER['REQUEST_URI']
17
                   $this->path = substr($this->path,1);    //> Removing leading slash
18
                } else
19
                   $this-path = $path;
20
        }
21
       
22
        public function add( $pattern, $app = null ) {
23
            $this->rule[$pattern] = $app;
24
                return $this;
25
        }
26
       
27
        public function dispatch() {
28
               
29
                foreach($this->rule as $pattern=>$app) {
30
                        if (preg_match('#^'.$pattern.'$#i',$this->path,$match)) {
31
                                print_r($match);
32
                                $this->run($app,$match);
33
                               
34
                                return true;
35
                        }
36
                }
37
               
38
                //> Nothing Matched run 404 error
39
                $this->run($this->default);
40
        }
41
       
42
        private function run($app,$match=array()) {
43
       
44
                //> First entry is all the string matched
45
                array_shift($match);
46
       
47
				$method=null;
48
                if ($app==null) {
49
                    $app = $match[0];
50
                } else if (is_array($app)) {
51
					$app = $app[0];
52
					$method = $app[1];
53
				}
54
               
55
                require($this->baseInclusionPath.$app.'.php');
56
               
57
                //> Remove the controller name
58
                array_shift($match);
59
				
60
				if ($method==null)
61
					$method = $match[0];
62
               
63
                //> Remove the method name
64
                array_shift($match);
65
               
66
                $app = 'Controller'.ucfirst($app);
67
                if (function_exists($app)) {
68
                        call_user_func_array($app,$match);
69
                } else {
70
                        $app = new $app;
71
                        call_user_func_array(array($app, $method), $match);
72
                }
73
        }
74
}