[+] добавлена маршрутизация

This commit is contained in:
rsgrinko committed 2022-06-21 21:21:26 +03:00
1 parent b33dbbf6a1
commit 51bfd64ef4
4 files changed
+102 -3

No files matched your search

+1 -1
View File
@@ -3,5 +3,5 @@ RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) /index.php?route=$1 [QSA,L]
RewriteRule (.*) /index.php?routeQuery=$1 [QSA,L]
</IfModule>
+6 -1
View File
@@ -4,6 +4,7 @@
use Core\Helpers\Cache;
use Core\Template;
use Core\CoreException;
use Core\Models\Router;
if (session_status() == PHP_SESSION_NONE) {
session_start();
@@ -65,4 +66,8 @@
}
} else {
$USER = null;
}
}
// запускаем маршрутизатор, передавая ему запрошенный адрес
Router::execute();
die();
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace Core\Models;
class Router
{
/**
* Страница 404 ошибки
*/
const ERROR_PAGE = '/^\/404$/';
/**
* @var array $routes Маршруты
*/
private static $routes = [];
/**
* Метод вывода 404 ошибки
*/
private static function notFound()
{
header('HTTP/1.0 404 Not Found');
echo '404 - Not Found';
}
/**
* Добавление маршрута в таблицу маршрутизации
*
* @param string $pattern Маршрут
* @param mixed $callback Callback функция
*
* @return void
*/
public static function route(string $pattern, $callback)
{
$pattern = '/^' . str_replace('/', '\/', $pattern) . '$/';
self::$routes[$pattern] = $callback;
}
/**
* Обработка маршрута
*
* @return mixed|void
*/
public static function execute()
{
foreach (self::$routes as $pattern => $callback) {
if (preg_match($pattern, $_SERVER['REQUEST_URI'], $params)) // сравнение идет через регулярное выражение
{
array_shift($params);
return call_user_func_array($callback, array_values($params));
}
}
if (in_array(self::ERROR_PAGE, array_keys(self::$routes), true)) {
return self::$routes[self::ERROR_PAGE]();
} else {
return self::notFound();
}
}
}
+32 -1
View File
@@ -1,2 +1,33 @@
<?php
// routes...
use Core\Models\Router;
use Core\Helpers\SystemFunctions;
Router::route('/', function () {
echo 'Домашняя станица';
});
Router::route('/404', function () {
header('HTTP/1.0 404 Not Found');
echo '404 - Page Not Found';
});
Router::route('blog/(\w+)/(\d+)', function ($category, $id) {
echo $category . ':' . $id;
});
class Test {
public static function run($num = 0, $d = 0) {
echo 'Hello World! ('.$num.') - ('.$d.')';
}
}
Router::route('/test/(\w+)/(\d+)', 'Test::run');