elaxer/router

简单快速的HTTP请求路由器

v3.0.0 2021-06-27 08:32 UTC

This package is not auto-updated.

Last update: 2024-09-30 00:52:37 UTC


README

简单快速的HTTP请求路由器。

安装

通过composer

composer require elaxer/router

使用

<?php

use Elaxer\Router\{PatternParser\PatternParser,RoutesCollection, RoutesFactory, RoutesFinder};

require __DIR__ . '/vendor/autoload.php';

// Contains routes and methods for adding
$collection = new RoutesCollection();

// Contains methods for processing URL pattern strings
$patternParser = new PatternParser();

// Provides a method for creating routes
$routesFactory = new RoutesFactory($patternParser);

// Adding Routes
$collection->addRoute($routesFactory->createRoute(['GET'], '/', 'indexHandler'));
// If it doesn't matter what the method should be, then the first parameter must be passed null
$collection->addRoute($routesFactory->createRoute(null, '/posts/{id}', fn(string $id): string => "Post with id $id"));
// You can define a parameter in a pattern
$collection->addRoute($routesFactory->createRoute(['GET'], '/news/{id}', fn(string $id): string => "News with id $id"));
// You can define a rule for a parameter as a regular expression
$collection->addRoute($routesFactory->createRoute(['DELETE'], '/users/{id:\d+}', 'deleteUserItemHandler'));


$path = '/news/13-01-news';
$method = 'GET';

// Finding a route by HTTP request
$routesFinder = new RoutesFinder($collection, $patternParser);
$foundRoute = $routesFinder->findRoute($path, $method);

// If route is found
if ($foundRoute !== null) {
    // Retrieve the handler passed as the third argument in the Route
    $handler = $foundRoute->getHandler();
    // Extracting parameters from url path
    $params = $patternParser->extractParametersFromPath($foundRoute->getPattern(), $path);

    // Further actions with the handler...
    if (is_callable($handler)) {
        // The response will be the string "News with id 13-01-news"
        $response = call_user_func_array($handler, $params);
        echo $response;
    }
}

路由命名

您可以通过指定构造函数的第四个参数来命名路由

$route = $routesFactory->createRoute(['GET'], '/users/{id}', 'getUserHandler', 'get-user');

$collection->addRoute($route);

您可以通过名称在路由器中找到路由

$route = $routesFinder->findRouteByName('get-user');

URL路径编译

通过使用Route::createPath方法并传递参数给它,您可以创建一个路径

$route = $routesFactory->createRoute(['GET'], '/users/{id}', 'getUserHandler');

echo $route->createPath(['id' => 25]); // will output /users/25