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

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

devlibs/routing
===============

a fast and flexible HTTP Router

1.0.0(8y ago)747BSD-3-ClausePHPPHP ^7.0

Since Oct 24Pushed 8y ago3 watchersCompare

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

READMEChangelog (1)Dependencies (1)Versions (2)Used By (0)

PHP Router
==========

[](#php-router)

[![Build Status](https://camo.githubusercontent.com/ba6b21fa97123c8c426b0c4095df816e235acb94179139105574257cad1e3d3f/68747470733a2f2f7472617669732d63692e6f72672f6465766c6962732f726f7574696e672e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/devlibs/routing)[![Coverage Status](https://camo.githubusercontent.com/6d5921acacb30b298f6114fb082a59c15da0b33b2d2a8caf1a149315e329814f/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f6465766c6962732f726f7574696e672f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/devlibs/routing?branch=master)[![Latest Stable Version](https://camo.githubusercontent.com/411a80ca198dd40dbe26634e406355338310f815430f77585c82d0b77776eefd/68747470733a2f2f706f7365722e707567782e6f72672f6465766c6962732f726f7574696e672f762f737461626c652e737667)](https://packagist.org/packages/devlibs/routing)[![Total Downloads](https://camo.githubusercontent.com/8da85a3380829f5d251e70b91140c1dd132ed6b755c006b0a1d46d3de04c606a/68747470733a2f2f706f7365722e707567782e6f72672f6465766c6962732f726f7574696e672f646f776e6c6f6164732e737667)](https://packagist.org/packages/devlibs/routing)[![License](https://camo.githubusercontent.com/c5e3d3fc6c736f0fa4a3a49493195f4698acad18ee088b71604c2d59c2fcb700/68747470733a2f2f706f7365722e707567782e6f72672f6465766c6962732f726f7574696e672f6c6963656e73652e737667)](LICENSE)

A fast, flexible and scalable HTTP router for PHP.

Features
--------

[](#features)

- **Grouping and nested group**
- **Easy to design RESTful API**
- **Full Tests**
- **Flexible and scalable**
- **No third-party library dependencies**
- **Named Param Placeholder**
- **Detect all request methods of the specify path**
- **Straightforward documentation**

Requirements
------------

[](#requirements)

- PHP - `7.0`, `7.1`, `7.2` and `master` are tested.

Install
-------

[](#install)

```
composer require devlibs/routing:1.0.0

```

Documentation
-------------

[](#documentation)

```
include '/path-to-vendor/autoload.php';

use DevLibs\Routing\Router;

// create an router instance
$settings = [
    'middlewares' => [
        'DebugMiddleware',
    ],
];
$router = new Router($settings);
```

### Register handler

[](#register-handler)

```
Router::handle($method, $path, $handler, $settings = null);
```

- `method` - `string` or `array`, **case-sensitive**, such as `GET`, `GET|POST`(split by `|`, without space), `['GET', 'POST']`
- `path` - the path **MUST** start with slash `/`, such as `/`, `/users`, `/users/`.
- `handler` - `mixed`, whatever you want.
- `settings` - user-defined settings.

Examples

MethodPathHandlerMatchedUnmatched`GET``/`handler`GET /``POST /` `get /``GET|POST``/users`handler`GET /users` `POST /users``['GET', 'POST']``/merchants`handler`GET /merchants` `POST /merchants``GET``/users/`handler`GET /users/foo` `GET /users/bar``GET``/orders/`handler`GET /orders/123456``GET /orders/letters`It also provides a few shortcuts for registering handler:

- `Router::delete`
- `Router::get`
- `Router::post`
- `Router::put`

```
$router->get('/', 'handler');

$router->handle('GET|POST', '/users', 'handler');

$router->handle(['GET', 'POST'], '/merchants', 'handler');

$router->get('/users/', 'handler');

$router->get('/orders/', 'handler');
```

### Dispatch request

[](#dispatch-request)

```
Router::dispatch($method, $path);
```

- `method` - request method, **case-sensitive**.
- `path` - URI path

If matched, an [`Route`](#route) instance which implements [`RouteInterface`](#routeinterface) will be returns, `null` otherwise.

```
$path = '/users/baz';
$route = $router->dispatch(Router::METHOD_GET, $path);
if (is_null($route)) {
    throw new \Exception('404 Not Found');
}

// handle requset
$handler = $route->handler(); // 'handler'
$params = $route->params(); // ['username' => 'baz']
$settings = $route->settings(); // $settings
```

### Route

[](#route)

Class `Route` implements [`RouteInterface`](#routeinterface), provides some basic methods.

You can also define your own `Route` class via the following code snippet:

```
Router::$routeClassName = 'namespace\MyRoute';
```

### RouteInterface

[](#routeinterface)

`Route` class **MUST** implements this interface, see [`RouteInterface`](src/RouteInterface.php) for more detail.

### Named Params Placeholder

[](#named-params-placeholder)

As the examples shown above, Router has ability to detect the param's value of the path.

In general, an placeholder pattern MUST be one of `` and ``, it will be converted to `([^/]+)` and `(regex)` respectively. You can also change it via replace the `Router::$replacePatterns` and `Router::$replacements`.

PatternPathMatchedParams`/guests/``/guests/小明`YES`['name' => '小明']``/guests/``/guests/foo`YES`['name' => 'foo']``/guests/``/guests/小明`NO`/orders/``/orders/123`YES`['order_id' => '123']``/orders/``/orders/letters`NO`/posts///``/posts/2017/10/hello-world`YES`['year' => '2017', 'month' => '10', title' => 'hello-world']``/posts///``/posts/201/10/hello-world`NO`/posts///``/posts/2017/9/hello-world`NO`/posts//``/posts/201710/hello-world`YES`['year' => '2017', 'month' => '10', title' => 'hello-world']`### Settings

[](#settings)

You can extend Router via `settings`, such as `param's default value` and `middleware` etc, but this topic are out of scope of this document.

### Grouping

[](#grouping)

Grouping is an powerful feature of Router for separating modules or API's versions. And this library also implements this feature, it allows nested grouping.

```
Router::group($prefix, array $settings = []);
```

- `prefix` - group prefix, it **MUST NOT** contains slash `/`.
- `settings` - settings for extending, it will inherits parent's settings.

```
// grouping
$v1Settings = [
    'version' => '1',
    'middlewares' => [
        'AuthMiddleware',
    ],
];
$v1 = $router->group('v1', $v1Settings);
$v1->get('/hello', 'hello');
$route = $router->dispatch(Router::METHOD_GET, '/v1/hello'); // matched
/**
 * [
 *     'version' => '1',
 *     'middlewares' => [
 *         'DebugMiddleware',
 *         'AuthMiddleware',
 *     ],
 * ];
 */
 var_dump($route->settings());
```

```
// nested group
$v1Users = $v1->group('users');
$v1Users->get('/', 'users');
$v1Users->get('/', 'user profile');
$route = $router->dispatch(Router::METHOD_GET, '/v1/users'); // matched
$route = $router->dispatch(Router::METHOD_GET, '/v1/users/bar'); // matched
```

### RESTful API

[](#restful-api)

As the examples shown above, it is obviously easy to design a RESTful API application.

```
$router->get('/products', 'products');
$router->post('/products', 'create product');
$router->get('/products/', 'product detail');
$router->put('/products/', 'update product');
$router->delete('/products/', 'delete product');
```

### Detect methods

[](#detect-methods)

In consideration of `OPTIONS` request, it provides an API for detecting all valid methods of the specify URI path.

```
Route::getAllowMethods($path, $methods = null);
```

- `path` - request URL path
- `methods` - `Router::$methods` defined some common request methods, but it does not include all request methods, you can specify the methods if the key method is not one of the `Router::$methods`.

```
$allowMethods = $router->getAllowMethods('/merchants'); // ['GET', 'POST']

```

FAQ
---

[](#faq)

### Package Not Found

[](#package-not-found)

Please add the following repository into `repositories` when `composer` complains about that `Could not find package devlibs/routing ...`.

```
{
    "type": "git",
    "url": "https://github.com/devlibs/routing.git"
}
```

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity13

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity58

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

Unknown

Total

1

Last Release

3125d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/17720932?v=4)[Razon Yang](/maintainers/RazonYang)[@razonyang](https://github.com/razonyang)

---

Top Contributors

[![razonyang](https://avatars.githubusercontent.com/u/17720932?v=4)](https://github.com/razonyang "razonyang (10 commits)")

---

Tags

fastflexiblegroupinghttpphprestful-apirouterhttprouterroutingRESTful API

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[miladrahimi/phprouter

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

20832.6k2](/packages/miladrahimi-phprouter)[wilaak/radix-router

High-performance radix tree based HTTP request router

612.8k5](/packages/wilaak-radix-router)

PHPackages © 2026

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