-
Notifications
You must be signed in to change notification settings - Fork 0
/
Router.php
64 lines (52 loc) · 1.55 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
<?php
class Router
{
private array $routes;
public static $_instance;
public function __construct()
{
$this->routes = [
"/" => "main.php",
"/user/create" => "create.php",
"/user/authorization" => "auth.php",
"/user/{id}/view" => "view.php",
"/user/{id}/update" => "update.php",
"/user/{id}/delete" => "delete.php",
];
}
public static function getInstance() : Router
{
if(null === self::$_instance) {
self::$_instance = new static();
}
return self::$_instance;
}
public function parse()
{
$uri = $_SERVER['REQUEST_URI'];
foreach ($this->routes as $route => $file) {
$match = true;
$param = [];
$routeParts = explode('/', $route);
$uriParts = explode('/', $uri);
foreach ($uriParts as $key => $uriPartName) {
if (!isset($routeParts[$key])){
$match = false;
continue;
}
if (substr($routeParts[$key], 0, 1) == '{' && substr($routeParts[$key], -1, 1) == '}') {
$match = true;
$param[trim($routeParts[$key], '{}')] = $uriParts[$key];
} elseif ($routeParts[$key] !== $uriParts[$key]) {
$match = false;
}
}
if ($match)
{
require $file;
break;
}
}
die(404);
}
}