/
admini
/
lesson4
Обзор
Документация
Войти
/
admini
/
lesson4
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
core/Router.php
92 строки
3 KB
admini
upload files
18 фев 2026, 08:58
Верифицирован
18 фев 2026, 08:58
784d3e8
Код
Авторство
О чём код?
<?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']); return 'OK'; } protected function matchRoute($path) { foreach ($this->routes as $route) { if ( preg_match("#^{$route['path']}$#", "/{$path}", $matches) && in_array($this->request->getMethod(), $route['method']) ) { // dump($matches); // dump($route); // dump($this->request->get_method()); // dump($this->route_params); foreach ($matches as $k => $v) { if (is_string($k)) { $this->route_params[$k] = $v; } } // dump($this->route_params); return $route; } } return false; } }