PHPackages                             fastd/routing - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. fastd/routing

ActiveLibrary[Framework](/categories/framework)

fastd/routing
=============

FastD routing component

v8.0.0(1mo ago)1420.2k7[1 PRs](https://github.com/fastdlabs/routing/pulls)4MITPHPPHP &gt;=8.2CI failing

Since Jun 20Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/fastdlabs/routing)[ Packagist](https://packagist.org/packages/fastd/routing)[ RSS](/packages/fastd-routing/feed)WikiDiscussions master Synced today

READMEChangelog (10)Dependencies (7)Versions (38)Used By (4)

FastD Routing
=============

[](#fastd-routing)

[![Build Status](https://camo.githubusercontent.com/1a1e63d68cf39c353b924af4da9b88c984f6b84b5789e314bfbc9029f0a9151e/68747470733a2f2f7472617669732d63692e6f72672f66617374646c6162732f726f7574696e672e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/fastdlabs/routing)[![Latest Stable Version](https://camo.githubusercontent.com/3620fa225e8768c072c1f25ec90950f68031a893e5449f3ef4fe2a3f3dc7073e/68747470733a2f2f706f7365722e707567782e6f72672f66617374642f726f7574696e672f762f737461626c65)](https://packagist.org/packages/fastd/routing)[![Total Downloads](https://camo.githubusercontent.com/b07892eca0674cbff41c61fe86451c40c4344f121502af716690aef58fa79055/68747470733a2f2f706f7365722e707567782e6f72672f66617374642f726f7574696e672f646f776e6c6f616473)](https://packagist.org/packages/fastd/routing)[![Latest Unstable Version](https://camo.githubusercontent.com/43b23e26f82fa5e4206d051d982aa9cd5320792313699ee6cea669f3d9fee853/68747470733a2f2f706f7365722e707567782e6f72672f66617374642f726f7574696e672f762f756e737461626c65)](https://packagist.org/packages/fastd/routing)[![License](https://camo.githubusercontent.com/4342484bc730017f779b4242099023bb8a7b28e4a440fdced09ce7c0c1924e4e/68747470733a2f2f706f7365722e707567782e6f72672f66617374642f726f7574696e672f6c6963656e7365)](https://packagist.org/packages/fastd/routing)

FastD Routing 是一个简单而强大的 PHP 路由器，支持路由嵌套、动态路由、模糊路由、中间件等功能。它依赖于 [Http](https://github.com/JanHuang/http) 组件，遵循 PSR-7 和 PSR-15 标准。

环境依赖
----

[](#环境依赖)

- PHP 8.2+
- [fastd/http](https://github.com/JanHuang/http)
- [psr/http-message](https://github.com/php-fig/http-message)
- [psr/http-server-handler](https://github.com/php-fig/http-server-handler)
- [psr/http-server-middleware](https://github.com/php-fig/http-server-middleware)

安装
--

[](#安装)

通过 Composer 安装:

```
Composer require "fastd/routing"

```

基础使用
----

[](#基础使用)

### Static routing

[](#static-routing)

```
use FastD\Http\ServerRequest;
use FastD\Routing\RouteCollection;
use Zend\Diactoros\Response;

$collection = new RouteCollection();

$collection->addRoute('GET', '/', function (ServerRequest $request, $handler) {
    return new Response(200, [], 'hello world');
});

$route = $collection->match(new ServerRequest('GET', '/')); // \FastD\Routing\Route

// 执行路由回调
$response = call_user_func_array($route->getCallback(), [$request, $handler]);
echo $response->getBody();
```

### Dynamic routing

[](#dynamic-routing)

```
use FastD\Http\ServerRequest;
use FastD\Routing\RouteCollection;
use Zend\Diactoros\Response;

$collection = new RouteCollection();

$collection->addRoute('GET', '/user/{name}', function (ServerRequest $request, $handler) {
    $name = $request->getAttribute('name');
    return new Response(200, [], 'hello ' . $name);
});

$route = $collection->match(new ServerRequest('GET', '/user/john'));

// 获取匹配的参数
$params = $route->getParameters(); // ['name' => 'john']
```

### 路由约束

[](#路由约束)

```
use FastD\Http\ServerRequest;
use FastD\Routing\RouteCollection;
use Zend\Diactoros\Response;

$collection = new RouteCollection();

// 数字参数约束
$collection->addRoute('GET', '/user/{id:[0-9]+}', function (ServerRequest $request, $handler) {
    $id = $request->getAttribute('id');
    return new Response(200, [], 'user id: ' . $id);
});

// 字母参数约束
$collection->addRoute('GET', '/profile/{name:[a-zA-Z]+}', function (ServerRequest $request, $handler) {
    $name = $request->getAttribute('name');
    return new Response(200, [], 'profile name: ' . $name);
});
```

### 路由组

[](#路由组)

```
use FastD\Http\ServerRequest;
use FastD\Routing\RouteCollection;
use Zend\Diactoros\Response;

$collection = new RouteCollection();

$collection->group('/api/v1', function (RouteCollection $collection) {
    $collection->addRoute('GET', '/users', function (ServerRequest $request, $handler) {
        return new Response(200, [], 'api v1 users');
    });

    $collection->addRoute('GET', '/posts', function (ServerRequest $request, $handler) {
        return new Response(200, [], 'api v1 posts');
    });
});

$route = $collection->match(new ServerRequest('GET', '/api/v1/users'));
```

### 路由中间件

[](#路由中间件)

```
use FastD\Http\ServerRequest;
use FastD\Routing\RouteCollection;
use FastD\Routing\RouteDispatcher;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Zend\Diactoros\Response;

// 自定义中间件
class ExampleMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 在处理前执行的操作
        $request = $request->withAttribute('timestamp', time());

        // 继续执行下一个中间件或路由处理器
        $response = $handler->handle($request);

        // 在处理后执行的操作
        return $response->withHeader('X-Middleware', 'processed');
    }
}

$collection = new RouteCollection();

$collection->addRoute('GET', '/middleware', function (ServerRequest $request, $handler) {
    return new Response(200, [], 'middleware example');
}, [
    ExampleMiddleware::class
]);

$dispatcher = new RouteDispatcher($collection);

$response = $dispatcher->dispatch(new ServerRequest('GET', '/middleware'));
echo $response->getBody();
```

### 多层中间件示例

[](#多层中间件示例)

```
use FastD\Http\ServerRequest;
use FastD\Routing\RouteCollection;
use FastD\Routing\RouteDispatcher;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Zend\Diactoros\Response;

// 定义多个中间件类
abstract class BaseNumberMiddleware implements MiddlewareInterface
{
    abstract protected function getMiddlewareName(): string;

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $number = $request->getAttribute('number') ?? 0;
        $number += 1; // 每个中间件将数字加1

        $processedHistory = $request->getAttribute('processed_history', []);
        $processedHistory[] = [
            'middleware' => $this->getMiddlewareName(),
            'value' => $number
        ];

        $request = $request->withAttribute('number', $number)
                           ->withAttribute('processed_history', $processedHistory);

        return $handler->handle($request);
    }
}

class NumberIncrementMiddleware1 extends BaseNumberMiddleware
{
    protected function getMiddlewareName(): string
    {
        return self::class;
    }
}

class NumberIncrementMiddleware2 extends BaseNumberMiddleware
{
    protected function getMiddlewareName(): string
    {
        return self::class;
    }
}

class NumberIncrementMiddleware3 extends BaseNumberMiddleware
{
    protected function getMiddlewareName(): string
    {
        return self::class;
    }
}

$collection = new RouteCollection();

$collection->addRoute('GET', '/process/{number:[0-9]+}', function (ServerRequest $request, $handler) {
    $finalValue = $request->getAttribute('number');
    $processedHistory = $request->getAttribute('processed_history', []);

    $data = [
        'original_number' => $request->getAttribute('number') - count($processedHistory),
        'final_number' => (int)$finalValue,
        'processed_by' => $processedHistory,
        'message' => 'Processing completed successfully'
    ];

    $json = json_encode($data, JSON_PRETTY_PRINT);
    return new Response(200, ['Content-Type' => 'application/json'], $json);
}, [
    NumberIncrementMiddleware1::class,
    NumberIncrementMiddleware2::class,
    NumberIncrementMiddleware3::class
]);

$dispatcher = new RouteDispatcher($collection);
$response = $dispatcher->dispatch(new ServerRequest('GET', '/process/5'));
echo $response->getBody();
// 输出: 原始数字5，经过3个中间件处理后变成8，同时显示每个中间件的处理过程
```

文档
--

[](#文档)

更多详细文档请参阅:

- [官方文档](https://github.com/JanHuang/fastD/wiki)
- [API 参考](https://github.com/JanHuang/routing/tree/master/src)
- [示例代码](https://github.com/JanHuang/routing/blob/master/example.php)

测试
--

[](#测试)

运行单元测试:

```
phpunit

```

贡献
--

[](#贡献)

欢迎提交 Issue 和 Pull Request 来帮助改进此项目！

License
-------

[](#license)

MIT License

###  Health Score

63

—

FairBetter than 99% of packages

Maintenance93

Actively maintained with recent releases

Popularity34

Limited adoption so far

Community23

Small or concentrated contributor base

Maturity87

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 91.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~114 days

Recently: every ~547 days

Total

36

Last Release

36d ago

Major Versions

v0.1.2 → v2.0.0-beta12016-05-01

v2.0.3 → v3.0.0-rc12017-01-10

v3.2.2 → 5.0.x-dev2020-01-06

v3.2.6 → v8.0.02026-05-28

PHP version history (5 changes)v0.1.0PHP &gt;=5.4

v2.0.0-beta1PHP &gt;=7.0

v3.0.0-rc1PHP &gt;=5.6

5.0.x-devPHP &gt;=7.1

v8.0.0PHP &gt;=8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/94c2bc821caf23977e1c3deea85e3cbc9a73a632e1afaf778638f7fe9da1c42b?d=identicon)[JanHuang](/maintainers/JanHuang)

---

Top Contributors

[![JanHuang](https://avatars.githubusercontent.com/u/7090871?v=4)](https://github.com/JanHuang "JanHuang (309 commits)")[![Gu1K](https://avatars.githubusercontent.com/u/6781018?v=4)](https://github.com/Gu1K "Gu1K (9 commits)")[![gmapnl](https://avatars.githubusercontent.com/u/41949435?v=4)](https://github.com/gmapnl "gmapnl (7 commits)")[![longxinH](https://avatars.githubusercontent.com/u/12230340?v=4)](https://github.com/longxinH "longxinH (6 commits)")[![RunnerLee](https://avatars.githubusercontent.com/u/7436388?v=4)](https://github.com/RunnerLee "RunnerLee (5 commits)")[![loyating](https://avatars.githubusercontent.com/u/5088390?v=4)](https://github.com/loyating "loyating (1 commits)")[![wangsir0624](https://avatars.githubusercontent.com/u/19991740?v=4)](https://github.com/wangsir0624 "wangsir0624 (1 commits)")

---

Tags

phprestfulroutingrouting

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/fastd-routing/health.svg)

```
[![Health](https://phpackages.com/badges/fastd-routing/health.svg)](https://phpackages.com/packages/fastd-routing)
```

###  Alternatives

[klein/klein

A lightning fast router for PHP

2.7k1.1M31](/packages/klein-klein)[nette/application

🏆 Nette Application: a full-stack component-based MVC kernel for PHP that helps you write powerful and modern web applications. Write less, have cleaner code and your work will bring you joy.

45715.9M1.1k](/packages/nette-application)[laravel/folio

Page based routing for Laravel.

603583.7k33](/packages/laravel-folio)[pecee/simple-router

Simple, fast PHP router that is easy to get integrated and in almost any project. Heavily inspired by the Laravel router.

675231.0k18](/packages/pecee-simple-router)[vlucas/bulletphp

A heierarchical resource-oriented micro-framework built on nested closures instead of route-based callbacks

41750.0k1](/packages/vlucas-bulletphp)[luthier/luthier

Improved routing, middleware support, authentication tools and more for CodeIgniter 3 framework

153125.0k](/packages/luthier-luthier)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
