horizom/dispatcher 问题修复 & 功能扩展

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

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

horizom/dispatcher

Composer 安装命令:

composer require horizom/dispatcher

包简介

A PSR-15 middleware dispatcher and pipeline for PHP 8+.

README 文档

README

A lightweight, dependency-free PSR-15 middleware dispatcher and pipeline for PHP 8+.

Total Downloads Latest Stable Version License

Features

  • Two dispatch strategies — flat-list Dispatcher and linked-list MiddlewarePipe
  • PSR-15 compliant — works with any MiddlewareInterface / RequestHandlerInterface implementation
  • Optional PSR-11 container — resolve middleware from any container by class name
  • Fluent API — chain add() calls on Dispatcher
  • Deep-clone safeMiddlewarePipe cloning does not share mutable state
  • Zero production dependencies beyond the PSR packages

Requirements

Requirement Version
PHP ^8.0
psr/http-message ^1.0 | ^2.0
psr/http-server-handler ^1.0
psr/http-server-middleware ^1.0
psr/container (optional) ^1.0 | ^2.0

Installation

composer require horizom/dispatcher

Concepts

Dispatcher — flat-list strategy

The Dispatcher keeps an ordered array of middlewares and an integer step counter. Calling dispatch() always resets the counter to 0 and calls handle() on the first entry. Each middleware is expected to call $handler->handle($request) to advance to the next step.

[MiddlewareA] → [MiddlewareB] → [TerminalHandler]
     ↓                ↓                ↓
  process()        process()        handle()

MiddlewarePipe — linked-list strategy

The MiddlewarePipeFactory builds an immutable linked list of MiddlewarePipe nodes. Each node holds a reference to the current entry and the next node. The chain is terminated by an EmptyRequestHandler sentinel that throws if reached.

MiddlewarePipe(A) → MiddlewarePipe(B) → MiddlewarePipe(Handler) → EmptyRequestHandler

Usage

Flat-list Dispatcher

use Horizom\Dispatcher\Dispatcher;

$dispatcher = new Dispatcher([
    new AuthMiddleware(),
    new LoggingMiddleware(),
    new FinalHandler(),   // implements RequestHandlerInterface
]);

$response = $dispatcher->dispatch($request);

Add middleware after construction with the fluent add() API:

$dispatcher = (new Dispatcher())
    ->add(new AuthMiddleware())
    ->add(new LoggingMiddleware())
    ->add(new FinalHandler());

$response = $dispatcher->dispatch($request);

Use dispatch() multiple times safely — the internal pointer is reset on every call:

$responseA = $dispatcher->dispatch($requestA);
$responseB = $dispatcher->dispatch($requestB); // works correctly

Invoke as a callable (e.g. in a routing layer):

$response = $dispatcher($request);

Linked-list MiddlewarePipe

use Horizom\Dispatcher\MiddlewarePipeFactory;

$factory = new MiddlewarePipeFactory();

$pipe = $factory->create([
    new AuthMiddleware(),
    new LoggingMiddleware(),
    new FinalHandler(),
]);

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

Merging pipelines

Sub-pipelines (instances of MiddlewarePipe) can be composed into a larger pipeline:

$authPipe = $factory->create([new AuthMiddleware(), new RateLimitMiddleware()]);

$pipe = $factory->create([
    $authPipe,               // merged in-place
    new LoggingMiddleware(),
    new FinalHandler(),
]);

Note: A sub-pipeline that contains an intermediate terminal RequestHandlerInterface (i.e. a handler that is not the EmptyRequestHandler sentinel) cannot be merged and will throw an InvalidArgumentException.

DispatcherFactory / MiddlewarePipeFactory

Both factories accept an optional MiddlewareResolverInterface argument:

use Horizom\Dispatcher\DispatcherFactory;
use Horizom\Dispatcher\MiddlewarePipeFactory;

$factory    = new DispatcherFactory($customResolver);
$dispatcher = $factory->create([AuthMiddleware::class, LoggingMiddleware::class]);

$pipeFactory = new MiddlewarePipeFactory($customResolver);
$pipe        = $pipeFactory->create([AuthMiddleware::class, FinalHandler::class]);

Resolving middleware from a PSR-11 container

Pass any PSR-11 ContainerInterface to MiddlewareResolver to enable string-based resolution:

use Horizom\Dispatcher\Dispatcher;
use Horizom\Dispatcher\MiddlewareResolver;

$resolver   = new MiddlewareResolver($container);
$dispatcher = new Dispatcher(
    [AuthMiddleware::class, LoggingMiddleware::class, FinalHandler::class],
    $resolver
);

$response = $dispatcher->dispatch($request);

The container must return an instance of MiddlewareInterface or RequestHandlerInterface, otherwise a TypeError is thrown with a descriptive message.

API Reference

Dispatcher

Method Description
__construct(array $middlewares = [], ?MiddlewareResolverInterface $resolver = null) Build the dispatcher, optionally pre-loading middlewares.
add(MiddlewareInterface|RequestHandlerInterface|string $middleware): self Append a middleware (fluent).
handle(ServerRequestInterface $request): ResponseInterface Advance one step in the stack (PSR-15).
dispatch(ServerRequestInterface $request): ResponseInterface Reset the pointer and run the full stack.
__invoke(ServerRequestInterface $request): ResponseInterface Alias for dispatch().

MiddlewarePipe

Method Description
__construct(MiddlewareInterface|RequestHandlerInterface $handler, RequestHandlerInterface $next) Create a pipeline node.
handle(ServerRequestInterface $request): ResponseInterface Execute this node and forward to $next if needed.
getHandler(): MiddlewareInterface|RequestHandlerInterface Return the current handler.
getNext(): RequestHandlerInterface Return the next node.
setNext(RequestHandlerInterface $next): void Replace the next node.

MiddlewareResolver

Method Description
__construct(?ContainerInterface $container = null) Optionally inject a PSR-11 container.
resolve(MiddlewareInterface|RequestHandlerInterface|string $middleware): MiddlewareInterface|RequestHandlerInterface Resolve a middleware instance (from container if string).

EmptyRequestHandler

Sentinel placed at the end of a MiddlewarePipe. Always throws RequestHandlerException.

Error Handling

Exception Thrown when
RequestHandlerException Dispatcher stack is exhausted / EmptyRequestHandler is reached.
TypeError A string middleware cannot be resolved (no container, or container returns invalid type).
InvalidArgumentException MiddlewarePipeFactory::create() receives an empty array, or a pipeline merge is impossible.

Testing

composer install
vendor/bin/phpunit

53 tests, 76 assertions.

License

MIT © Roland Edi

horizom/dispatcher 适用场景与选型建议

horizom/dispatcher 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 256 次下载、GitHub Stars 达 0, 最近一次更新时间为 2022 年 07 月 10 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 horizom/dispatcher 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-07-10