php final class Router private path private args array function setPat

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
final class Router {
private $path;
private $args = array();
function setPath($path)
{
$path = trim($path, '/\\');
$path .= DIRSEP;
if(!is_dir($path))
throw new Exception('Invalid controller path: `'.$path .'`');
$this->path = $path;
}
function delegate()
{
$this->getController($file, $controller, $action, $args);
if(!is_readable($file))
die('404 Not Found!');
require_once($file);
$class = 'Controller_'.$controller;
$controller = new $class;
if(!is_callable(array($controller, $action)))
$action = 'not_found';
$controller->$action();
}
private function getController(&$file, &$controller, &$action, &$args)
{
$route = (empty($_GET['route'])) ? '' : $_GET['route'];
if(empty($route))
$route = 'index';
$route = trim($route, '/\\');
$parts = explode('/', $route);
$cmd_path = $this->path;
foreach ($parts as $part)
{
$fullpath = $cmd_path.'controller_'.$part;
if(is_dir($fullpath))
{
$cmd_path .= $part.DIRSEP;
array_shift($parts);
continue;
}
if(is_file($fullpath.'.php'))
{
$controller = $part;
array_shift($parts);
break;
}
}
if(empty($controller))
$controller = 'index';
$action = array_shift($parts);
if(empty($action))
$action = 'index';
$file = $cmd_path.'controller_'.$controller.'.php';
$args = $parts;
}
}
?>