itmo-php-course/engine/core/Router.php

60 lines
2.2 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
require_once 'Autoloader.php';
Autoloader::init();
class Router
{
// массив маршрутов
private $routes;
public function __construct()
{
// указываем путь к роутам (ROOT - путь к базовой дериктории
// '/config/routes.php' - путь к созданному файлу с роутами
$routesPath = __DIR__ . '/../routes.php';
// здесь мы присваиваем свойству $this->routes массив,
// который хранится в файле routes.php, при помощи - include
$this->routes = include($routesPath);
}
// метод будет принимать управление от фронтконтроллера
public function run()
{
echo ("Запуск контроллера!");
// var_dump($this->routes);
// обратимся к методу getURI()
$uri = $this->getURI();
echo $uri;
foreach ($this->routes as $uriPattern => $path) {
// echo "<br>$uriPattern -> $path";
if (preg_match("~$uriPattern~", $uri)) {
$segments = explode('/', $path);
$controllerName = array_shift($segments) . 'Controller';
// делает первую букву строки заглавной
$controllerName = ucfirst($controllerName);
var_dump($controllerName);
// выводим имя контроллера
$actionName = 'action' . ucfirst(array_shift($segments));
$controllerFile = __DIR__ . '/../app/controller/' . $controllerName . '.php';
var_dump($controllerFile);
if (file_exists($controllerFile)) {
include_once($controllerFile);
}
$controllerObject = new $controllerName;
$result = $controllerObject->$actionName();
// выводим название экшена
echo '<br>' . $result;
}
}
}
private function getURI()
{
if (!empty($_SERVER['REQUEST_URI'])) {
return trim($_SERVER['REQUEST_URI'], '/');
}
}
}