PHPackages                             pvettori/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. pvettori/router

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

pvettori/router
===============

PHP Router: app routing for humans.

0.1.8(3y ago)017MITPHPPHP &gt;=7.1

Since Mar 13Pushed 3y ago1 watchersCompare

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

READMEChangelog (7)Dependencies (3)Versions (11)Used By (0)

PHP Router: app routing for humans
==================================

[](#php-router-app-routing-for-humans)

[![Latest Version](https://camo.githubusercontent.com/30f30926f71f29057dcee6d807d4280c85c0e6b4e56193cc7eec5c22c4743d45/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f76657273696f6e2d302e312e372d6f72616e6765)](https://github.com/pvettori/router/releases)[![PHP Version](https://camo.githubusercontent.com/84adf325783b828a59f11b8b04574f5e478dae247b0027d507f6eeac6c8e4ed1/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d254532253839254135372e312d626c7565)](https://www.php.net/)[![MIT License](https://camo.githubusercontent.com/f8df3091bbe1149f398a5369b2c39e896766f9f6efba3477c63e9b4aa940ef14/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e)](https://github.com/pvettori/router/blob/master/LICENSE)

A simple router utility for applications.

Web applications are, in their essence, software that respond to an HTTP request.
This simple router offers a quick and easy way to define the routes of your application.

Contents
--------

[](#contents)

1. [Quick start](#quick-start)
    1a. [Installation](#installation)
    1b. [Use example](#use-example)
2. [Usage](#usage)
3. [Advanced Usage](#advanced-usage)
4. [Reference](#reference)
    4a. [PVproject\\Routing\\Middleware](#pvproject%5Crouting%5Cmiddleware)
    4b. [PVproject\\Routing\\Route](#pvproject%5Crouting%5Croute)
    4c. [PVproject\\Routing\\Router](#pvproject%5Crouting%5Crouter)

Quick start
-----------

[](#quick-start)

### Installation

[](#installation)

```
composer require pvettori/router

```

### Use example

[](#use-example)

```
use PVproject\Routing\Route;
use PVproject\Routing\Router;

Router::create()->addRoute(Route::get('/home', function () {
    http_response_code(200);
    exit('Home');
}))->run();
```

Usage
-----

[](#usage)

You can create a route:

```
$route = Route::get('/home', function () { echo 'This is the home page.'; });
```

Then add it to a router:

```
$router = Router::create()->addRoute($route);
```

And finally run the router:

```
$router->run();
```

You may want to define a route with path parameters:

```
$route = Route::get('/path/{param}', function ($param) {
    echo 'This is the route parameter: '.$param;
});
```

> Note that path parameters are automatically passed as arguments with the same name to the action function (in no particular order).

> Path parameters can also be injected as associative array through the `$parameters` argument.

Or have access to the request object in your route action (the router handles a PSR-7 Request object):

```
$route = Route::get('/path', function ($request) {
    echo 'This is the HTTP method: '.$request->getMethod();
});
```

> Note that any action function argument named `$request` gets automatically assigned the server request object.

And maybe define a path prefix for your subsequent routes:

```
$router = Router::create()->setPrefix('/admin');
$router->setRoute('/login' function () {
    echo 'This route is /admin/login';
});
```

Advanced Usage
--------------

[](#advanced-usage)

In order to restrict a route to respond to specific methods an array of methods can be passed as additional argument.

```
$route = Route::create('/path', function () { /* code */ }, ['PUT', 'PATCH']);
// alternative way
$route = Router::create()->setRoute('path/', function () { /* code */ }, ['PUT', 'PATCH']);
```

The Route `$action` argument accepts the name of a class method or the name of an invokable class (*a class with the magic method `__invoke()`*).

```
$route = Route::get('/path', '\ActionClass->action');
$route = Route::get('/path', '\ActionClass::staticAction');
$route = Route::get('/path', '\InvokableClass');
```

A Route can have middleware assigned to it.
Middleware functions and classes must all accept at least two arguments, the first being the server request (modified by the previous middleware) and the second being the next handler.

```
function middleware_function($request, $handler) {
    // code executed before next handler...
    $response = $handler($request);
    // code executed after next handler...

    return $response;
}

class MiddewareClass extends \PVproject\Routing\Middleware {
    public function __invoke(
        RequestInterface $request,
        callable $handler
    ): ResponseInterface {
        // code executed before next handler...
        $response = $handler($request);
        // code executed after next handler...

        return $response;
    }
}

$route = Route::create('/path', function ($request) { return $response; })
    ->withMiddleware(
        'middleware_function',
        'MiddewareClass'
    );
```

Middleware may require extra arguments.
Those arguments can be passed by entering the middleware as an array with the first item being the middleware function or class and the subsequent items being the extra arguments in exact order.

```
function middleware_function($request, $handler, $extra) {
    return $response;
}

$route = Route::create('/path', function ($request) { return $response; })
    ->withMiddleware(
        ['middleware_function', 'extra_argument'],
        'MiddewareClass'
    );
```

Routes can also be grouped by prefix:

```
$router = Router::create()->addRouteGroup('/admin', [
    Route::create('/login', function ($request) { return $response; })
    Route::create('/home', function ($request) { return $response; })
], [
    ['middleware_function', 'extra_argument'],
    'MiddewareClass'
]);
```

Extra arguments can be provided to the router.
Such arguments are automatically injected in the route action.

```
// arguments passed on Router creation
$router = Router::create([
    'arguments' => [
        'extra1' => 'value1',
        'extra2' => 'value2',
    ]
]);
// arguments passed on Router run
$router = Router::create()->run([
    'extra1' => 'value1',
    'extra2' => 'value2',
]);
```

Reference
=========

[](#reference)

PVproject\\Routing\\Middleware
------------------------------

[](#pvprojectroutingmiddleware)

Abstract class to be extend in order to help create middleware classes.

### **Middleware** Methods

[](#middleware-methods)

#### `__invoke(RequestInterface $request, callable $handler): ResponseInterface`

[](#__invokerequestinterface-request-callable-handler-responseinterface)

The only required method of a Middleware class.

ArgumentTypeDescription`$request`*RequestInterface*The server request object (modified by previous middleware).`$handler`*callable*The next middleware or route action.PVproject\\Routing\\Route
-------------------------

[](#pvprojectroutingroute)

A class representing a single route.
The Route object is immutable.

### **Route** Methods

[](#route-methods)

#### `__construct(string $path, $action, [array $methods], [string $name])`

[](#__constructstring-path-action-array-methods-string-name)

Create a new Route.

ArgumentTypeDescription`$path`*string*The route path.
Path parameters can be declared with braces (ex.: "`/path/{param}`").
*NOTE: Parameter names start with a letter or underscore, followed by any number of letters, numbers, or underscores.*
Path parameters can also be restricted by appending a colon and a regex to the parameter name (ex.: "`/path/{param:\d+}`").
*NOTE: The prameter name cannot be "this" as it would be injected as the reserved word `$this`.*
*NOTE: The regex does not accept the `/` character and the `{` , `}` , `^` and `$` metacharacters.*`$action`*mixed*A function, function name, class method name or invokable class name that gets executed if the route matches the current server request.`$methods`*array*Optional.
An array of HTTP request methods.
Valid methods are: "`GET`", "`PUT`", "`POST`", "`PATCH`", "`DELETE`", "`HEAD`", "`OPTIONS`". If not declared then the route matches any method.`$name`*string*Optional.
A name for the route.#### `getAction(): callable`

[](#getaction-callable)

Returns the route action function.

#### `getAttributes(): array`

[](#getattributes-array)

Returns the route attributes.

#### `getMetohds(): array`

[](#getmetohds-array)

Returns the route methods.

#### `getMiddleware(): array`

[](#getmiddleware-array)

Returns the route middleware.

#### `getName(): ?string`

[](#getname-string)

Returns the route name.

#### `getPath(): string`

[](#getpath-string)

Returns the declared route path.

#### `matches(RequestInterface $request, [array &$pathParams]): bool`

[](#matchesrequestinterface-request-array-pathparams-bool)

Check if the route matches a given request object.

ArgumentTypeDescription`$request`*RequestInterface*A request object.`&$pathParams`*array*Optional.
An array populated with the defined path parameters.#### `withAttributes(array $attributes): Route`

[](#withattributesarray-attributes-route)

Return a new instance with an added attributes.
Attributes are passed by name as arguments to the action.

ArgumentTypeDescription`$attributes`*array*An associative array containing attributes.
Attribute names must match this regex: `^[a-zA-Z_][a-zA-Z0-9_]*$`.#### `withMiddleware($middleware [, $middleware] [, ...])`

[](#withmiddlewaremiddleware--middleware--)

Returns a new Route object with middleware assigned to it.

ArgumentTypeDescription`$middleware`*string|callable*A middleware class or function.
If extra arguments need to be passed to the middleware then the definition can be expressed as an array with the first argument being the middleware class or function and the subsequent arguments being the extra arguments in exact order.#### `withName(string $name): Route`

[](#withnamestring-name-route)

Returns a new Route object with the specified name.

ArgumentTypeDescription`$name`*string*The route name.#### `withPath(string $path): Route`

[](#withpathstring-path-route)

Returns a new Route object with the specified path.

ArgumentTypeDescription`$path`*string*The route path.
See [Route::\_\_construct()](#route-methods) for details.### **Route** Factory Methods

[](#route-factory-methods)

#### `Route::create(string $path, $action, [array $methods])`

[](#routecreatestring-path-action-array-methods)

Create a new Route.

#### `Route::get(string $path, $action)`

[](#routegetstring-path-action)

Create a new Route with the "`GET`" method.

#### `Route::put(string $path, $action)`

[](#routeputstring-path-action)

Create a new Route with the "`PUT`" method.

#### `Route::post(string $path, $action)`

[](#routepoststring-path-action)

Create a new Route with the "`POST`" method.

#### `Route::patch(string $path, $action)`

[](#routepatchstring-path-action)

Create a new Route with the "`PATCH`" method.

#### `Route::delete(string $path, $action)`

[](#routedeletestring-path-action)

Create a new Route with the "`DELETE`" method.

PVproject\\Routing\\Router
--------------------------

[](#pvprojectroutingrouter)

The router class.

### **Router** Methods

[](#router-methods)

#### `__construct([array $config])`

[](#__constructarray-config)

Create a new Router.

ArgumentTypeDescription`$config`*array*A configuration array.
Available configuration options: `arguments`, `fallback`, `prefix`.#### `getRoute(string $name): ?Route`

[](#getroutestring-name-route)

Get the a named route.

#### `getRoutes(): array`

[](#getroutes-array)

Get the defined routes.

#### `run([array $arguments])`

[](#runarray-arguments)

Run the router.

ArgumentTypeDescription`$arguments`*array*An associative array of extra arguments injected into the action function.
Arguments injected by default are: `$parameters`, `$request`, `$route`.#### `setPrefix([string $prefix]): Router`

[](#setprefixstring-prefix-router)

Set a route prefix. The prefix is prepended to the path of every subsequent route.
Routes delcared prior to this method are not affected.

ArgumentTypeDescription`$prefix`*string*Optional.
The path prefix.
*NOTE: calling `->setPrefix()` without argument removes the prefix.*#### `setFallback($action): Router`

[](#setfallbackaction-router)

Set an action that gets executed when no route match is found.

ArgumentTypeDescription`$action`*mixed*The fallback action.#### `addRoute(Route $route): Router`

[](#addrouteroute-route-router)

Add a Route.

ArgumentTypeDescription`$route`*Route*The Route object.#### `addRouteGroup(string $prefix, array $routes, [array $middleware]): Router`

[](#addroutegroupstring-prefix-array-routes-array-middleware-router)

Add multiple routes grouped by prefix.
Previously declared prefixes are prepended to the group prefix.
Subsequent routes are not affected by the group prefix.

ArgumentTypeDescription`$prefix`*string*The grouped routes prefix.`$routes`*array*The grouped routes.`$middleware`*array*An array of middleware applied to all routes in the group.#### `run([array $arguments])`

[](#runarray-arguments-1)

Run the route matching.

ArgumentTypeDescription`$arguments`*array*Associative array of arguments injected into the action function. Route attributes and path parameters are also injected as arguments.
Route attributes have precendence over run arguments.
Path parameters have precendence over Route attributes and run arguments.#### `setRoute(string $path, $action, [array $methods], [string $name]): Route`

[](#setroutestring-path-action-array-methods-string-name-route)

Adds a route and returns the Route object.
See [Route::\_\_construct()](#route-methods) for details.

### **Router** Factory Methods

[](#router-factory-methods)

#### `Router::create([array $config])`

[](#routercreatearray-config)

Create a new Router.

ArgumentTypeDescription`$config`*array*See [Router::\_\_construct()](#router-methods).

###  Health Score

21

—

LowBetter than 19% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity44

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 ~52 days

Recently: every ~110 days

Total

10

Last Release

1422d ago

### Community

Maintainers

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

---

Top Contributors

[![pvettori-mamoka](https://avatars.githubusercontent.com/u/181086143?v=4)](https://github.com/pvettori-mamoka "pvettori-mamoka (13 commits)")

---

Tags

httpresponserequestpsrpsr-7restweb servicerouterroutingrouteweb app

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[psr/http-factory

PSR-17: Common interfaces for PSR-7 HTTP message factories

1.9k692.9M1.9k](/packages/psr-http-factory)[fig/http-message-util

Utility classes and constants for use with PSR-7 (psr/http-message)

39489.0M274](/packages/fig-http-message-util)[psr/http-server-handler

Common interface for HTTP server-side request handler

175101.3M921](/packages/psr-http-server-handler)[elementaryframework/water-pipe

URL routing framework and requests/responses handler for PHP

254.6k4](/packages/elementaryframework-water-pipe)

PHPackages © 2026

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