/
mr.fork
/
less4
Обзор
Документация
Войти
/
mr.fork
/
less4
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
core/Router.php
95 строк
3 KB
mr.fork
upload files
18 фев 2026, 08:56
Верифицирован
18 фев 2026, 08:56
b9b29ec
Код
Авторство
О чём код?
<?php namespace PHPFramework; class Router { protected Request $request; protected Response $response; protected array $routes = []; protected array $route_params = []; public function __construct(Request $request, Response $response) { $this->request = $request; $this->response = $response; } public function add($path, $callback, $method):self { $path = trim($path, '/'); if(is_array($method)) { $method = array_map('strtoupper', $method); } else{ $method = [strtoupper($method)]; } $this->routes[] = [ 'path' => "/".$path, 'callback' => $callback, 'middleware' => null, 'method' => $method, 'needToken' => 'true', ]; return $this; } public function get($path, $callback):self { return $this->add($path, $callback, 'get'); } public function post($path, $callback):self { return $this->add($path, $callback, 'post'); } public function getRoutes(): array { return $this->routes; } public function dispatch(): mixed { $path = $this->request->getPath(); $route = $this->matchRoute($path); if (!$route) { $this->response->setResponseCode(404); echo '404 - Page not found'; die; } // dump($route); if (is_array($route['callback'])) { $route['callback'][0] = new $route['callback'][0]; } return call_user_func($route['callback']); // dump($route); return "ok"; } protected function matchRoute($path): mixed { foreach ($this->routes as $route) { if ( preg_match("#^{$route['path']}$#", "/{$path}", $matches) && in_array($this->request->getMethod(), $route['method']) ) { // dump('match', $matches); // dump($route); // dump($this->request->getMethod()); foreach ($matches as $key => $value) { if (is_string($key)) { $this->route_params[$key] = $value; } } // dump($this->$route_params); return $route; } } return false; } }