Route v2

 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
<?php
class Route {
private $request;
private $controller;
private $action;
private $method;
public function __construct() {
$this->request = Request::uri();
$this->defineRoute();
}
public function defineRoute() {
$request = rtrim(ltrim($this->request, '/'), '/');
$this->method = Request::method();
$actions = explode('/', $request);
if (!empty($actions[0])) {
$this->controller = ucfirst(strtolower($actions[0])).'Controller';
if (!empty($actions[1])) {
$action = strtolower($actions[1]);
if (preg_match('#^[a-z-]+$', $action)) {
$action = str_replace('-', ' ', $action);
$action = ucwords($action);
$action = str_replace(' ', '', $action);
$this->action = $action;
}
} else {
if (!class_exists($this->controller)) {
$this->controller = 'MainController';
$this->action = ucfirst(strtolower($actions[0]));
} else {
$this->action = 'Index';
}
}
} else {
$this->controller = 'MainController';
$this->action = 'Index';
}
}
public function render() {
var_dump($this);
if (class_exists($this->controller)) {
$object = new $this->controller;
$method = $this->method.$this->action;
if (method_exists($object, $method)) {
return $object->$method();
}
}
return Application::error(404);
}
}