-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRouter.php
More file actions
executable file
·49 lines (37 loc) · 1.21 KB
/
Copy pathRouter.php
File metadata and controls
executable file
·49 lines (37 loc) · 1.21 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
<?php
class Router
{
private $routes;
public function __construct()
{
$routesPath = 'config/routes.php';
$this->routes = include($routesPath);
}
private function getURI()
{
$uri = $_SERVER['REQUEST_URI'];
if (!empty($uri)) {
return trim($uri, '/');
}
}
public function run()
{
$uri = $this->getURI();
foreach ($this->routes as $uriPattern => $path) {
if (preg_match("~$uriPattern~", $uri)) {
$internalRoute = preg_replace("~$uriPattern~", $path, $uri);
$segments = explode('/', $internalRoute);
$controllerName = ucfirst(array_shift($segments)) . 'Controller';
$actionName = 'action' . ucfirst(array_shift($segments));
$params = $segments;
$controllerFile = 'controller/' . $controllerName . '.php';
if (file_exists($controllerFile)) {
include_once($controllerFile);
}
$controller = new $controllerName;
session_start();
return call_user_func_array([$controller, $actionName], $params);
}
}
}
}