-
Notifications
You must be signed in to change notification settings - Fork 0
/
Router.php
75 lines (67 loc) · 2.08 KB
/
Router.php
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
<?php
class Route {
private $url;
private $verb;
private $controller;
private $method;
private $params;
public function __construct($url, $verb, $controller, $method){
$this->url = $url;
$this->verb = $verb;
$this->controller = $controller;
$this->method = $method;
$this->params = [];
}
public function match($url, $verb) {
if($this->verb != $verb){
return false;
}
$partsURL = explode("/", trim($url,'/'));
$partsRoute = explode("/", trim($this->url,'/'));
if(count($partsRoute) != count($partsURL)){
return false;
}
foreach ($partsRoute as $key => $part) {
if($part[0] != ":"){
if($part != $partsURL[$key])
return false;
} //es un parametro
else
$this->params[$part] = $partsURL[$key];
}
return true;
}
public function run(){
$controller = $this->controller;
$method = $this->method;
$params = $this->params;
(new $controller())->$method($params);
}
}
class Router {
private $routeTable = [];
private $defaultRoute;
public function __construct() {
$this->defaultRoute = null;
}
public function route($url, $verb) {
//$ruta->url //no compila!
foreach ($this->routeTable as $route) {
if($route->match($url, $verb)){
//TODO: ejecutar el controller//ejecutar el controller
// pasarle los parametros
$route->run();
return;
}
}
//Si ninguna ruta coincide con el pedido y se configuró ruta por defecto.
if ($this->defaultRoute != null)
$this->defaultRoute->run();
}
public function addRoute ($url, $verb, $controller, $method) {
$this->routeTable[] = new Route($url, $verb, $controller, $method);
}
public function setDefaultRoute($controller, $method) {
$this->defaultRoute = new Route("", "", $controller, $method);
}
}