Add support for params in route with new route dispatcher
This commit is contained in:
parent
0111ef9525
commit
e8d8e0e95b
12 changed files with 393 additions and 115 deletions
77
src/Routing/Router.php
Normal file
77
src/Routing/Router.php
Normal file
|
@ -0,0 +1,77 @@
|
|||
<?php
|
||||
|
||||
namespace Core\Routing;
|
||||
|
||||
use Core\Http\Request;
|
||||
|
||||
class Router
|
||||
{
|
||||
/**
|
||||
* List of routes
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected static array $routes = [];
|
||||
|
||||
/**
|
||||
* Add GET route
|
||||
*
|
||||
* @param string $route
|
||||
* @param string $controller
|
||||
* @param string $action
|
||||
* @return void
|
||||
*/
|
||||
public static function get(string $route, string $controller, string $action): void
|
||||
{
|
||||
self::register($route, $controller, $action, "GET");
|
||||
}
|
||||
|
||||
/**
|
||||
* Add POST route
|
||||
*
|
||||
* @param string $route
|
||||
* @param string $controller
|
||||
* @param string $action
|
||||
* @return void
|
||||
*/
|
||||
public static function post(string $route, string $controller, string $action): void
|
||||
{
|
||||
self::register($route, $controller, $action, "POST");
|
||||
}
|
||||
|
||||
/**
|
||||
* Register route
|
||||
*
|
||||
* @param string $route
|
||||
* @param string $controller
|
||||
* @param string $action
|
||||
* @param string $method
|
||||
* @return void
|
||||
*/
|
||||
public static function register(string $route, string $controller, string $action, string $method): void
|
||||
{
|
||||
// Convert route with parameters into regex
|
||||
$routeRegex = preg_replace('/\{([a-zA-Z0-9_]+)\}/', '(?P<\1>[a-zA-Z0-9_-]+)', $route);
|
||||
$routeRegex = '#^' . $routeRegex . '$#';
|
||||
|
||||
self::$routes[$method][$routeRegex] = [
|
||||
'controller' => $controller,
|
||||
'action' => $action,
|
||||
'original' => $route,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch router and run application
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function dispatch(): void
|
||||
{
|
||||
// Create request
|
||||
$request = new Request($_POST + $_FILES);
|
||||
|
||||
// Dispatch router
|
||||
RouteDispatcher::dispatch($request, self::$routes);
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue