-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRouter.php
More file actions
60 lines (50 loc) · 1.85 KB
/
Copy pathRouter.php
File metadata and controls
60 lines (50 loc) · 1.85 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
class Router {
private $routes = [];
// Register routes
public function add($method, $route, $action) {
$this->routes[] = [
'method' => strtoupper($method), // GET, POST, etc.
'route' => $route,
'action' => $action
];
}
// Match route and execute the action
public function dispatch() {
$method = $_SERVER['REQUEST_METHOD']; // GET, POST, etc.
$uri = $this->getUri();
foreach ($this->routes as $route) {
if ($method == $route['method'] && $this->matchRoute($uri, $route['route'])) {
$this->executeAction($route['action']);
return;
}
}
// If no route matched, show a 404
echo "404 Not Found";
}
// Extract the URI without the domain and query string
private function getUri() {
$uri = $_SERVER['REQUEST_URI'];
$uri = parse_url($uri, PHP_URL_PATH); // Remove query string
return trim($uri, '/'); // Remove leading/trailing slashes
}
// Check if the route matches the current URI
private function matchRoute($uri, $route) {
// Convert the route to regex (support for parameters like {id})
$route = preg_replace('/\{([a-zA-Z0-9_]+)\}/', '(?P<$1>[^/]+)', $route);
$route = "/^" . $route . "$/";
return preg_match($route, '/' . $uri);
}
// Call the controller/action based on the route
private function executeAction($action) {
list($controller, $method) = explode('@', $action);
// Instantiate the controller class and call the method
if (class_exists($controller) && method_exists($controller, $method)) {
$controllerInstance = new $controller();
$controllerInstance->$method();
} else {
echo "Action not found!";
}
}
}
?>