PHPackages                             york8/router - 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. [HTTP &amp; Networking](/categories/http)
4. /
5. york8/router

ActiveLibrary[HTTP &amp; Networking](/categories/http)

york8/router
============

一个简单的基于 PSR 7 的 PHP 路由器，良好的分层和扩展结构

0.1.1(8y ago)2201MITPHPPHP ~7.1

Since Aug 15Pushed 8y agoCompare

[ Source](https://github.com/york8/php-router)[ Packagist](https://packagist.org/packages/york8/router)[ Docs](https://github.com/york8/php-router)[ RSS](/packages/york8-router/feed)WikiDiscussions master Synced 3d ago

READMEChangelog (2)Dependencies (3)Versions (4)Used By (1)

PHP-Router
==========

[](#php-router)

[![Latest Stable Version](https://camo.githubusercontent.com/f57974829b46dc14040c6e94c9de3c34506b547129b56d85b081e171cc4c1d41/68747470733a2f2f706f7365722e707567782e6f72672f796f726b382f726f757465722f762f737461626c65)](https://packagist.org/packages/york8/router)[![Total Downloads](https://camo.githubusercontent.com/1d483614af7862d2a2800b16dd50a5c3277742bf349c8e10e85d82ba0b27b2ee/68747470733a2f2f706f7365722e707567782e6f72672f796f726b382f726f757465722f646f776e6c6f616473)](https://packagist.org/packages/york8/router)[![Latest Unstable Version](https://camo.githubusercontent.com/343bc1679d50b4939723207df14e2731357c4d3eb4885dea014cc4fe37cca1c3/68747470733a2f2f706f7365722e707567782e6f72672f796f726b382f726f757465722f762f756e737461626c65)](https://packagist.org/packages/york8/router)[![License](https://camo.githubusercontent.com/6860cf989408139dae907af3a7a8f49d346753f1547b241b612b131d93ea5304/68747470733a2f2f706f7365722e707567782e6f72672f796f726b382f726f757465722f6c6963656e7365)](https://packagist.org/packages/york8/router)

一个简单的基于 [PSR 7](http://www.php-fig.org/psr/psr-7/) 的 PHP 路由器，良好的分层和扩展结构

- 基于 [PSR 7](http://www.php-fig.org/psr/psr-7/) HTTP 消息接口
- 面向接口编程，灵活扩展
- RESTful 风格路由
- PCRE 正则匹配

### Authors

[](#authors)

- [York](https://github.com/york8)

### Easy to install with composer

[](#easy-to-install-with-composer)

```
$ composer require york8/router
```

### Usage

[](#usage)

#### How to use：

[](#how-to-use)

##### 1. 创建带默认路由失败处理器的路由器对象，

[](#1-创建带默认路由失败处理器的路由器对象)

```
$router = new Router(function notFound() { ... });
```

##### 2. 构建路由规则，将规则与处理器关联起来

[](#2-构建路由规则将规则与处理器关联起来)

```
$router->get(...);
$router->post(...);
$router->put(...);
$router->head(...);
$router->option(...);
$router->delete(...);
$router->addRuler(...);
```

通过实现 **[MatcherInterface](src/MatcherInterface.php)** 接口来实现自己的规则匹配器， 然后实现 **[Ruler](src/RulerInterface.php)** 接口来组合不同的[匹配器](src/Matcher)从而定制自己的规则， 也可以使用 **$rule-&gt;addMatcher** 方法来给默认的规则实现(**[Ruler](src/Ruler.php)**)添加额外的匹配器， 最后使用 **$router-&gt;addRuler** 来添加规则。

已实现的匹配器可以在[这里](src/Matcher)找到：

- [Host](src/Matcher/HostMatcher.php)匹配器：用来匹配请求头 Host
- [Method](src/Matcher/MethodMatcher.php)匹配器：用来匹配请求方法
- [Path](src/Matcher/PathMatcher.php)匹配器：路径匹配器，用来匹配请求路径

路径匹配器支持正则匹配，定义如下：

```
class PathMatcher implements MatcherInterface
    /**
     * @param \string[] $paths 需要匹配的路径列表，路径规则如下：
     *  /path/to/target
     *  /path/to/(pattern)/target 括号内为正则表达式
     *  /path/:attr1(pattern)/to/:attr2(pattern) 命名的正则表达式，匹配到值将设置到请求对象的 attributes 中
     * @param string $prefix
     * @param bool $isCaseSensitive 是否匹配大小写，默认忽略大小写
     */
    public function __construct(array $paths, $prefix = null, bool $isCaseSensitive = false)
    {
        // ...
    }

    /**
     * @param string $path
     * @param string[]|null $attrs
     * @return bool
     * @throws \RuntimeException
     */
    public function match($path, array &$attrs = null): bool
    {
        // ...
    }

    // ...
}
```

使用说明：

1. 正则表达式必须使用圆括号括起来“**(patther)**”，括号内的内容可以为空，表示匹配任意字符
2. 命名正则表达式，冒号开头，形如"**:name**"开始的单词命名紧跟的正则表达式，路径匹配成功后， 命名正则匹配到的路径值将返回给属性结果，可以通过 attrs\[name\] 捕获
3. 路径默认是前缀匹配的，可以在路径末尾添加 "$" 来变成全路径匹配，如 "/foo" 可以匹配 "/foo/bar"，但 "/foo$" 则不能能匹配 "/foo/bar"

格式示例如下：

```
/path/to/foo

```

普通路径前缀匹配；

```
path/to/(\\w+)

```

非命名的正则表达式，不捕获任何路径值；

```
/path/to/:name/list

```

使用命名的空正则表达式，将捕获到路径中的某一节并将其赋值给 "name" 属性，通过 attrs 返回；

```
/paht/to/:foo(\\w+)-:bar(\\d+)/account/:name

```

使用命名的表达式，捕获匹配到的路径值并赋值给 "foo"、"bar" 和 "name" 属性，通过 attrs 返回。

##### 3. 初始化请求和响应对象

[](#3-初始化请求和响应对象)

使用实现了 [PSR 7](http://www.php-fig.org/psr/psr-7/) 规范的第三方库来初始化构建请求对象和响应对象，如：

- [zend-diactoros](https://github.com/zendframework/zend-diactoros)
- [guzzle](https://github.com/guzzle/psr7)
- ...

##### 4. 路由请求获取到对应的处理器

[](#4-路由请求获取到对应的处理器)

```
$attrs = [];
$handler = $router->route($request, $attrs);
```

**attrs** 用来接收路由过程中捕获到的参数信息，如路径规则中定义的的参数，具体返回值由使用的路由规则和匹配器决定。

##### 5. 使用处理器处理请求

[](#5-使用处理器处理请求)

```
$response = $handler->handle($request, $response);
```

#### An Example Route

[](#an-example-route)

```
// 1. create Router with default not found handler
$router = new Router(function (ServerRequestInterface $request, ResponseInterface $response) {
    $response = $response->withStatus(404);
    $body = $response->getBody();
    $body->write('Not Found: ' . $request->getUri()->getPath());
    return $response;
});
// 2. build the router rules
$router->get(
    '/account/:username',
    function (ServerRequestInterface $request, ResponseInterface $response) {
        $username = $request->getAttribute('username');
        $body = $response->getBody();
        $body->write("Hello, $username!");
        return $response;
    }
);

// 3. initialize the request
$request = ServerRequest::fromGlobals();

// use the 'php://output' stream for the response body directly
$body = fopen('php://output', 'w+');
// 3. initialize the response
$response = new Response(200, [], $body);

// 4. route the request and get the handler
$attrs = [];
$handler = $router->route($request, $attrs);

// set the request attributes with the 'attrs' of route result
foreach ($attrs as $attrName => $attrValue) {
    $request = $request->withAttribute($attrName, $attrValue);
}

// 5. handle the request
$response = $handler->handle($request, $response);
```

### License

[](#license)

This project is licensed under the MIT License.

License can be found [here](LICENSE).

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity9

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~96 days

Total

3

Last Release

3003d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/f2e9047ab03fd9d26c0e915fb310145415891c35c0a7c55eb95f8a37de0ff433?d=identicon)[york8](/maintainers/york8)

---

Top Contributors

[![york8](https://avatars.githubusercontent.com/u/22073873?v=4)](https://github.com/york8 "york8 (18 commits)")

---

Tags

psr-7routerroutingroute

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/york8-router/health.svg)

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

###  Alternatives

[aura/router

Powerful, flexible web routing for PSR-7 requests.

5231.5M67](/packages/aura-router)[league/route

Fast routing and dispatch component including PSR-15 middleware, built on top of FastRoute.

6633.1M115](/packages/league-route)[pmjones/auto-route

Automatically routes HTTP request to action classes.

20158.6k6](/packages/pmjones-auto-route)[miladrahimi/phprouter

A powerful, lightweight, and very fast HTTP URL router for PHP projects.

20832.6k2](/packages/miladrahimi-phprouter)[contributte/api-router

RESTful Router for your Apis in Nette Framework - created either directly or via attributes

20802.8k3](/packages/contributte-api-router)

PHPackages © 2026

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