Advertisement
markeze

Untitled

Feb 10th, 2023 (edited)
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.09 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\core;
  4.  
  5. class Router
  6. {
  7.     private mixed $routes;
  8.  
  9.     public function __construct()
  10.     {
  11.         $this->routes = include(ROOT.'/src/config/routers.php');
  12.     }
  13.  
  14.     // returns request string
  15.     private function getURI(): string
  16.     {
  17.         if(!empty($_SERVER['REQUEST_URI']))
  18.         {
  19.             return trim($_SERVER['REQUEST_URI'],'/');
  20.         }
  21.         return false;
  22.     }
  23.     public function run(): void
  24.     {
  25.         $uri = $this->getURI(); // Получаем URI
  26.         foreach($this->routes as $uriPattern => $path) // Проходимся по массиву для перехода по классам
  27.         {
  28.             if(preg_match("~$uriPattern~", $uri)) // проверяем есть ли в массиве URI по которому мы перешли
  29.             {
  30.  
  31.                 $internalRoute = preg_replace("~$uriPattern~", $path, $uri); // в строке запроса, мы ищем параметры по шаблону в массиве
  32.                 // и подставляем в $path - $1, $2
  33.  
  34.                 $segments = explode('/', $internalRoute); // делим ссылку
  35.                 $controllerName = array_shift($segments) . 'Controller'; // получаем контроллер
  36.                 $controllerName = ucfirst($controllerName);
  37.  
  38.                 $actionName = 'action' . ucfirst(array_shift($segments)); // получаем action (метод)
  39.  
  40.                 $controllerFile = ROOT . '/src/controllers/' . $controllerName . '.php'; // ищем путь
  41.  
  42.                 if(file_exists($controllerFile)) // проверка на файл
  43.                 {
  44.                     include_once($controllerFile);
  45.                 }
  46.                 $controllerObject = new $controllerName;
  47.                 $result = call_user_func_array(array($controllerObject, $actionName), $segments); // вызываем нужный action(метод) у контроллера
  48.  
  49.                 if($result != null)
  50.                 {
  51.                     break;
  52.                 }
  53.             }
  54.         }
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement