Guest User

Untitled

a guest
Mar 19th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. <?php
  2.  
  3. class Router
  4. {
  5.  
  6. private $routes;
  7.  
  8. public function __construct()
  9. {
  10. $routesPath = ROOT.'/config/routes.php';
  11. $this->routes = include($routesPath);
  12. }
  13.  
  14. // Return type
  15.  
  16. private function getURI()
  17. {
  18. if (!empty($_SERVER['REQUEST_URI'])) {
  19. return trim($_SERVER['REQUEST_URI'], '/');
  20. }
  21. }
  22.  
  23. public function run()
  24. {
  25. $uri = $this->getURI();
  26.  
  27. foreach ($this->routes as $uriPattern => $path) {
  28.  
  29. if(preg_match("~$uriPattern~", $uri)) {
  30.  
  31. /* echo "<br>Где ищем (запрос, который набрал пользователь): ".$uri;
  32. echo "<br>Что ищем (совпадение из правила): ".$uriPattern;
  33. echo "<br>Кто обрабатывает: ".$path; */
  34.  
  35. // Получаем внутренний путь из внешнего согласно правилу.
  36.  
  37. $internalRoute = preg_replace("~$uriPattern~", $path, $uri);
  38.  
  39. /* echo '<br>Нужно сформулировать: '.$internalRoute.'<br>'; */
  40.  
  41. $segments = explode('/', $internalRoute);
  42.  
  43. $controllerName = array_shift($segments).'Controller';
  44. $controllerName = ucfirst($controllerName);
  45.  
  46.  
  47. $actionName = 'action'.ucfirst(array_shift($segments));
  48.  
  49. $parameters = $segments;
  50.  
  51.  
  52. $controllerFile = ROOT . '/controllers/' .$controllerName. '.php';
  53. if (file_exists($controllerFile)) {
  54. include_once($controllerFile);
  55. }
  56.  
  57. $controllerObject = new $controllerName;
  58. /*$result = $controllerObject->$actionName($parameters); - OLD VERSION */
  59. /*$result = call_user_func(array($controllerObject, $actionName), $parameters);*/
  60. $result = call_user_func_array(array($controllerObject, $actionName), $parameters);
  61.  
  62. if ($result != null) {
  63. break;
  64. }
  65. }
  66.  
  67. }
  68. }
  69. }
Add Comment
Please, Sign In to add comment