barretstorck/server-request-router 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

barretstorck/server-request-router

Composer 安装命令:

composer require barretstorck/server-request-router

包简介

A PSR-15 compliant HTTP middleware that routes requests to other middlewares

README 文档

README

A PSR-15 compliant ServerRequestInterface router that allows for conditional routing to different middlewares based on the properties of the ServerRequest. This allows for only using middlewares when they are needed, and when the middlewares are provided as lazy objects then they can skip instantiation entirely if not needed, saving time and server resources.

Installation

composer require barretstorck/server-request-router

Examples

Hello world

<?php

use BarretStorck\ServerRequestRouter\Router;
use GuzzleHttp\Psr7\ServerRequest;
use GuzzleHttp\Psr7\Response;
use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;

// Create a new instance of the Router.
$router = new Router();

// Add middleware to the router.
// In this case, it's a single middleware that will be used for all requests.
$router->addMiddleware(
    new Response(200, ['Content-Type' => 'text/plain'], 'Hello world!'), // Define the response to always return.
);

// Create a ServerRequest object representing the current HTTP request,
// populated from PHP's global variables like $_SERVER, $_GET, $_POST, etc.
$request = ServerRequest::fromGlobals();

// Process the request through the router and obtain the corresponding Response object.
// Since we've only added one middleware that returns a response, this will always return that response.
$response = $router->handle($request);

// Create an instance of SapiEmitter, which will handle sending the response back to the client.
$emitter = new SapiEmitter();
// Send the response to the client, including headers and body.
$emitter->emit($response);

Echo value from URL path

<?php

use BarretStorck\ServerRequestRouter\Router;
use GuzzleHttp\Psr7\ServerRequest;
use GuzzleHttp\Psr7\Response;
use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;

// Initialize the router.
$router = Router::make()
    // Start a new branch for specific paths.
    ->branch()
        // Define the path pattern this branch handles.
        // The pattern matches paths starting with "/echo/",
        // followed by a captured group named 'my_path_value'
        // consisting of 1 to 64 alphanumeric characters.
        // The 'i' flag makes the pattern case-insensitive.
        ->hasPath('/^\/echo\/(?<my_path_value>[a-z0-9]{1,64})$/i')
        // Add middleware for this specific path.
        // This anonymous function will be executed if the path matches.
        ->addMiddleware(function($request) {
            // Retrieve the 'my_path_value' captured from the path.
            $pathValue = $request->getAttribute('my_path_value');
            // Create a new Response object.
            // Status code 200 (OK), Content-Type header set to 'text/plain',
            // and the body is set to the captured path value.
            $response = new Response(200, ['Content-Type' => 'text/plain'], $pathValue);
            // Return the created response.
            return $response;
        })
    // Return to the root level of the router.
    ->root()
    // Add a default middleware at the root level.
    // This will be executed if no other branch matches.
    // It sets a default 404 (Not Found) response.
    ->addMiddleware(new Response(404));

// Create a ServerRequest object from the global PHP variables (e.g., $_SERVER, $_GET, $_POST).
$request = ServerRequest::fromGlobals();

// Handle the request using the router and get the corresponding response.
$response = $router->handle($request);

// Create a new SapiEmitter instance. This is responsible for sending the response to the client.
$emitter = new SapiEmitter();
// Emit the response. This sends the response headers and body to the client.
$emitter->emit($response);

Larger example with API endpoints

Includes:

  • Middlewares that are performed for all requests
    • ErrorCatcherMiddleware
    • MessageLoggerMiddleware
    • RateLimiterMiddleware
  • A branch to handle when the request has contents in the body
    • Return a 413 "Content Too Large" response if the body is too big
    • Otherwise pass the request to an AntiMalwareMiddleware
  • A branch to handle the "/comments" API endpoint
    • GET method calls CommentsGetMiddleware
    • PUT method calls CommentsPutMiddleware
    • POST method extracts the comment ID from the URL path, sets it as an attribute on the Request, and calls CommentsPostMiddleware
    • DELETE method calls CommentsDeleteMiddleware
  • A default response of 404 "Not Found" for all other requests
<?php

use BarretStorck\ServerRequestRouter\Router;
use GuzzleHttp\Psr7\ServerRequest;
use GuzzleHttp\Psr7\Response;
use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;

// Create the router.
$router = Router::make()

    // Add middlewares that will be used for all requests.
    ->addMiddleware(
        new ErrorCatcherMiddleware(), // Catch and handle any thrown errors
        new MessageLoggerMiddleware(), // Log all requests and responses
        new RateLimiterMiddleware(), // Limit the number of requests per minute
    )

    // Create a branch to handle if the request has a body.
    ->branch()
        ->hasBody()
        ->branch()
            // If the request has a body that is larger than 1GB, return a 413 error.
            ->hasBodyLargerThan(pow(1024, 3))
            ->addMiddleware(new Response(413, ['content-type' => 'text/plain'], 'Content Too Large'))
        ->parent()

        // If the request has a body that is an acceptable size, check for malware.
        ->addMiddleware(new AntiMalwareMiddleware())
    
    // Go to the root of the router
    ->root()

    // Add a branch to handle the /comments API
    ->branch()
        ->hasPath('/^\/comments/i')
        ->branch()
            // Handle GET /comments
            ->hasMethod('GET')
            ->addMiddleware(new CommentsGetMiddleware())
        ->parent()
        ->branch()
            // Handle PUT /comments
            ->hasMethod('PUT')
            ->addMiddleware(new CommentsPutMiddleware())
        ->parent()
        ->branch()
            // Fetch the comment_id from the path
            ->hasPath('/^\/comments\/(?<comment_id>\d+)$/i')
            ->branch()
                // Handle POST /comments/<comment_id>
                ->hasMethod('POST')
                ->addMiddleware(new CommentsPostMiddleware())
            ->parent()
            ->branch()
                // Handle DELETE /comments/<comment_id>
                ->hasMethod('DELETE')
                ->addMiddleware(new CommentsDeleteMiddleware())
    
    // Go back to the root of the router
    ->root()

    // Send a 404 response if no route was matched
    ->addMiddleware(new Response(404, ['content-type' => 'text/plain'], 'Not Found'));

$request = ServerRequest::fromGlobals();

$response = $router->handle($request);


$emitter = new SapiEmitter();

$emitter->emit($response);

The code above provides a Router that matches the following flow chart: Flow chart

barretstorck/server-request-router 适用场景与选型建议

barretstorck/server-request-router 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 01 月 15 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「router」 「middleware」 「psr-15」 「psr15」 「request handler」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 barretstorck/server-request-router 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 barretstorck/server-request-router 我们能提供哪些服务?
定制开发 / 二次开发

基于 barretstorck/server-request-router 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 2
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 22
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-01-15