-
Notifications
You must be signed in to change notification settings - Fork 0
/
Router.php
79 lines (71 loc) · 2.7 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
76
77
78
79
<?php
namespace Details;
use Details\controllers\ProductController;
use Details\controllers\UserController;
use Details\controllers\InvoiceController;
use Details\models\User;
class Router
{
public array $getRoutes = [];
public array $postRoutes = [];
public Database $db;
public function __construct()
{
$this->db = new Database();
}
public function get($url, $fn)
{
$this->getRoutes[$url] = $fn;
}
public function post($url, $fn)
{
$this->postRoutes[$url] = $fn;
}
public function resolve() //detects what is the current route
{
$currentUrl = $_SERVER['REQUEST_URI'] ?? "/";
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';
// Check if the URL matches the pattern
if (preg_match('~^/checkout/detail/(\d+)$~', $currentUrl, $matches)) {
// Extract the ID from the matches array
$id = $matches[1];
$_SESSION['invoice_id'] = $id;
$this->get("/checkout/detail", [InvoiceController::class, "show"]);
$fn = $this->getRoutes["/checkout/detail"];
} else {
if ($method === 'GET') {
$fn = $this->getRoutes[$currentUrl] ?? null;
} else if ($method === 'POST' && $action === 'signup') {
$fn = [UserController::class, 'signup'];
} else if ($method === 'POST' && $action === 'signin') {
$fn = [UserController::class, 'signin'];
} else if ($method === 'POST' && $action === 'create_product') {
$fn = [ProductController::class, 'create'];
} else if ($method === 'POST' && $action === 'update_product') {
$fn = [ProductController::class, 'update'];
} else {
$fn = $this->postRoutes[$currentUrl] ?? null;
}
}
if ($fn) {
// echo "<pre>";
// var_dump($this->getRoutes);
// echo "</pre>";
call_user_func($fn, $this); //aw functiona render bka ka dawa krawa ka rendery view aka wa $this routery pe anerin wakw parameter
}
// else {
// echo 'page not found';
// }
}
public function renderView($view, $params = []) //products/index.php
{
foreach ($params as $key => $value) {
$$key = $value;
}
ob_start(); //cashing out in browser put it wont send to the browser it will save it in the buffer
include_once __DIR__ . "/views/$view.php"; //and save it in content varibale
$content = ob_get_clean(); //now view file is saved in $content and its inside _layout
include_once __DIR__ . "/views/_layout.php";
}
}