libra-php/stellar-router

StellarRouter 是一个 PHP 库,提供了一种基于属性的强大路由器,用于将 HTTP 请求映射到请求处理器。

dev-main 2024-01-15 19:46 UTC

This package is auto-updated.

Last update: 2024-09-15 21:06:23 UTC


README

Discord Community PHP Version License PHP Composer

🌌 StellarRouter 是一个高级 PHP 库,通过一个复杂的基于属性的路由器来提升您的 Web 应用程序的路由能力。通过无缝地将 HTTP 请求映射到指定的请求处理器,StellarRouter 使开发者能够以无与伦比的精确性和效率在复杂的路由领域中导航。🌟

主要特性

  • 全面的 HTTP 路由:支持标准 HTTP 方法,如 GET、POST、PUT、PATCH 和 DELETE,实现灵活的请求处理。
  • 路由中间件绑定:轻松将中间件附加到路由上,提高模块化和请求处理的健壮性。
  • 直观且易于开发者使用:拥有直观且优雅的 API,无论开发者经验水平如何,都能确保易用性。
  • 路由分组:将相关路由组织到逻辑组中,简化代码管理并增强代码库的清晰度。
  • 命名路由:为路由分配有意义的名称,促进语义化和易于维护的路由结构。
  • 动态路由参数:轻松提取动态路由参数,促进动态内容处理和数据操作。
  • 路由前缀:实现路由前缀以适应版本控制或分类,优化 API 设计。

安装

使用 Composer 无缝安装 StellarRouter

composer require libra-php/stellar-router

用法

探索一个基本示例,以掌握 StellarRouter 的能力

use StellarRouter\{Router, Get, Post, Group};

#[Group(prefix: "/v1", middleware: ["auth"])]
class PhotoController
{
    #[Get('/photos/{photo}/edit', 'photos.edit')]
    public function edit($photo)
    {
        return "edit: $photo";
    }

    #[Post('/photos', 'photos.create')]
    public function create()
    {
        return ["success" => true];
    }

    # Note: you can also write regex route paths (parenthesis required)
    #[Get('/(mom|dad)', 'photos.parents')]
    public function parents(): void
    {
        return ["success" => true];
    }
}

// Instantiate the router
$router = new Router;

// Automatically register route attributes from the controller class and methods
$router->registerClass(PhotoController::class);

// Alternatively, manually add routes using the registerRoute method
// Example: $router->registerRoute(new Route("/test", "GET"));

// Process the request based on the HTTP method and request URI
$route = $router->handleRequest('GET', '/v1/photos/42/edit');

// Extract route details
$handlerClass = $route->getHandlerClass();
$handlerMethod = $route->getHandlerMethod();
$routeParameters = $route->getParameters();

// Instantiate the appropriate controller class
$controller = new $handlerClass();

// Invoke the designated endpoint, passing necessary arguments
$response = $controller->$handlerMethod(...$routeParameters);

// Output the response
print($response); // Output: 'edit: 42'

许可证

StellarRouter 是开源软件,根据 MIT 许可证 许可。