vilnis/easy-route

易于使用的PHP路由器。

v1.0.0 2023-12-29 21:26 UTC

This package is not auto-updated.

Last update: 2024-09-22 23:28:24 UTC


README

EasyRoute是一个轻量级的PHP路由器,用于处理HTTP请求并将它们路由到相应的控制器方法。

功能

  • 简单易用的路由机制
  • 支持带参数的动态路由
  • 与PHP 8.1.0或更高版本兼容

安装

您可以通过Composer安装EasyRoute。在终端中运行以下命令

composer require vilnis/easy-route

用法

基本用法

<?php
use EasyRoute\Router;
use EasyRoute\Exceptions\RouteNotFoundException;
use EasyRoute\Exceptions\MethodNotAllowedException;
use MyCustomNamespace\MyCustomController; // Replace with your custom namespace

// Include Composer's autoloader
require_once __DIR__ . '/vendor/autoload.php';

// Create a new router instance
$router = new EasyRoute\Router();

// Define routes using addRoute() with HTTP methods
$router->addRoute('GET', '/users', [MyCustomController::class, 'index']);
$router->addRoute('POST', '/users', [MyCustomController::class, 'create']);
$router->addRoute('PUT', '/users/{id/d}/{text/t}', [MyCustomController::class, 'update']);
$router->addRoute('PATCH', '/users/{id/d}', [MyCustomController::class, 'modify']);
$router->addRoute('DELETE', '/users/{id/d}/{text/t}', [MyCustomController::class, 'delete']);

try {
    // Get request method and URI
    $method = $_SERVER['REQUEST_METHOD'];
    $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

    // Match the route
    [$routeHandler, $params] = $router->match($method, $uri);

    if ($routeHandler !== null) {
        // Execute the corresponding method based on the matched route
        [$controller, $method] = $routeHandler;
        $controllerInstance = new $controller();

        // Handle the matched route with extracted parameters dynamically as an array
        $response = call_user_func_array([$controllerInstance, $method], [$params]);

        // Output the response or handle it further
        echo $response;
    } else {
        throw new RouteNotFoundException('Route not found.');
    }
} catch (RouteNotFoundException $e) {
    // Handle RouteNotFoundException
    http_response_code(404);
    echo '404 Not Found: ' . $e->getMessage();
} catch (MethodNotAllowedException $e) {
    // Handle MethodNotAllowedException
    http_response_code(405);
    echo '405 Method Not Allowed: ' . $e->getMessage();
}

带有类型标记的路由(/d 和 /t)

  • /users/{id/d}/{text/t}:期望两个参数

    • {id/d}:需要为id提供一个数字(数值)。
    • {text/t}:期望字母文本。
  • /users/{id/d}:期望一个参数

    • {id/d}:需要为id提供一个数字(数值)。

无类型标记的路由

  • /products/{category}:此路由包含{category}参数,没有特定的类型标记{category/t}{category/d}
    • {category}:接受各种类型的参数(数字、字母字符等)。