-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRouter.php
More file actions
45 lines (36 loc) · 1.09 KB
/
Router.php
File metadata and controls
45 lines (36 loc) · 1.09 KB
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
<?php
namespace MVC;
class Router {
public $getRoutes = [];
public $postRoutes = [];
public function get($url, $fn) {
$this->getRoutes[$url] = $fn;
}
public function post($url, $fn) {
$this->postRoutes[$url] = $fn;
}
public function checkRoute() {
$currentUrl = strtok($_SERVER['REQUEST_URI'], '?') ?? '/';
$method = $_SERVER['REQUEST_METHOD'];
$routes = ($method === 'POST') ? $this->postRoutes : $this->getRoutes;
$fn = $routes[$currentUrl] ?? null;
$this->executeFunction($fn);
}
public function executeFunction($fn) {
if ($fn) {
call_user_func($fn, $this);
} else {
header("HTTP/1.0 404 Not Found");
$this->render('templates/error404');
}
}
public function render($view, $data = []) {
foreach($data as $key=>$value) {
$$key = $value;
}
ob_start();
include_once __DIR__ . '/views/' . $view . '.php';
$content = ob_get_clean();
include __DIR__ . '/views/layout.php';
}
}