php_engine/core/Router.php
2025-01-20 21:35:13 +03:00

46 lines
1.4 KiB
PHP

<?php
class Router {
private $routes;
public function __construct() {
$routesPath = __DIR__ . '/../routes.php';
$this->routes = include($routesPath);
}
public function run() {
$uri = $this->getURI();
if (!$uri) {
$obj = new MainController();
$obj -> actionIndex();
return null;
}
$controllerName = "";
foreach($this->routes as $uriPattern => $path)
{
if(preg_match("~$uriPattern~", $uri)){
// проверка: если есть совпадение, то выведет путь из routes.php
$segments = explode('/', $path);
$controllerName = array_shift($segments) . 'Controller';
$controllerName = ucfirst($controllerName);
$actionName = 'action' . ucfirst(array_shift($segments));
$controllerObject = new $controllerName;
$result = $controllerObject->$actionName();
}
}
if (!$controllerName) {
// echo("Else Router");
// Page Not Found
$obj = new MainController();
$obj -> actionNotFound();
}
}
private function getURI(){
if(!empty($_SERVER['REQUEST_URI'])){
return trim($_SERVER['REQUEST_URI'], '/');
}
}
}