1 <?php
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 18 19
20 class MagratheaRoute {
21
22 private $defaultControl = "Home";
23 private $defaultAction = "Index";
24 private $routes = null;
25 private $controllers = array();
26
27 protected static $inst = null;
28 public static function Instance(){
29 if(!isset(self::$inst)){
30 self::$inst = new MagratheaRoute();
31 }
32 return self::$inst;
33 }
34 35 36
37 private function MagratheaRoute(){}
38
39 40 41 42 43
44 public function SetRoute($routes){
45 $this->routes = array_change_key_case( array_map('strtolower', $routes), CASE_LOWER );
46 foreach ($this->routes as $key => $value) {
47 $r = explode("/", $key);
48 if(empty($r[1]))
49 $this->controllers[$r[0]][0] = $value;
50 else
51 $this->controllers[$r[0]][$r[1]] = $value;
52 }
53 return $this;
54 }
55
56 57 58 59 60 61
62 public function Defaults($control="Home", $action="Index"){
63 $this->defaultControl = $control;
64 $this->defaultAction = $action;
65 return $this;
66 }
67
68 69 70 71 72 73 74
75 public function Route(&$control, &$action, &$params=null){
76 $params = array();
77 if(!@empty($_GET["magrathea_control"])) $control = $_GET["magrathea_control"];
78 if(!@empty($_GET["magrathea_action"])) $action = $_GET["magrathea_action"];
79 if(!@empty($_GET["magrathea_params"])) $params = $_GET["magrathea_params"];
80 $control = strtolower($control);
81 $action = strtolower($action);
82 $this->LookForRoute($control, $action, $params);
83 if(empty($control)) $control = strtolower($this->defaultControl);
84 if(empty($action)) $action = strtolower($this->defaultAction);
85 return $this;
86 }
87
88 89 90 91 92 93 94
95 private function LookForRoute(&$control, &$action, &$params){
96
97 if( empty($this->controllers[$control]) ) return;
98 if( !empty($this->controllers[$control][$action]) ){
99 $newRoute = $this->UnbuildUrl($this->controllers[$control][$action]);
100 } else {
101 if( !empty($this->controllers[$control][0]) )
102 $newRoute = $this->UnbuildUrl($this->controllers[$control][0]);
103 else
104 return;
105 }
106 if(!empty($newRoute["control"])) $control = $newRoute["control"];
107 if(!empty($newRoute["action"])) $action = $newRoute["action"];
108 if(!empty($newRoute["params"])) $params = $newRoute["params"];
109 }
110
111 112 113 114 115 116 117
118 public function RebuildUrl($control="", $action="", $params=""){
119 $url = $control;
120 if(empty($action)) return $url;
121 $url .= "/".$action;
122 if(empty($params)) return $url;
123 $url .= "/".$params;
124 return $url;
125 }
126
127 128 129 130 131 132
133 public function UnbuildUrl($url){
134 $parse = explode("/", $url);
135 $ret = array();
136 $ret["control"] = $parse[0];
137 if(!empty($parse[1])) $ret["action"] = $parse[1];
138 if(!empty($parse[2])) $ret["params"] = $parse[2];
139 return $ret;
140 }
141
142
143 }
144
145
146 ?>