PHPackages                             bobbynarvy/highway - 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. bobbynarvy/highway

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

bobbynarvy/highway
==================

Simple routing for PHP. PSR-7 and PSR-15 compatible.

0.5.0(7y ago)8481[1 issues](https://github.com/bobbynarvy/highway/issues)[1 PRs](https://github.com/bobbynarvy/highway/pulls)MITPHPPHP ^7.1CI failing

Since Oct 11Pushed 5mo ago2 watchersCompare

[ Source](https://github.com/bobbynarvy/highway)[ Packagist](https://packagist.org/packages/bobbynarvy/highway)[ RSS](/packages/bobbynarvy-highway/feed)WikiDiscussions master Synced 2w ago

READMEChangelog (1)Dependencies (6)Versions (4)Used By (0)

Highway
=======

[](#highway)

[![Build Status](https://camo.githubusercontent.com/362884811425b645b68f79e39e4de9b2fcd0347795d0e71edc0eb8c1c798fbe9/68747470733a2f2f7472617669732d63692e6f72672f626f6262796e617276792f686967687761792e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/bobbynarvy/highway)

Simple routing for PHP. PSR-7 and PSR-15 compatible.

**Highway** is a component for routing HTTP requests to their handlers.

Install
-------

[](#install)

Via Composer

```
$ composer require bobbynarvy/highway
```

Usage
-----

[](#usage)

**Highway** can be used as a stand-alone router that can be integrated in any PHP script as well as a PSR-15 middleware.

### Basic usage: As a stand-alone router

[](#basic-usage-as-a-stand-alone-router)

A basic scenario where the router is used would look like:

```
// on index.php...

use Highway\{Route, Router};

// PSR-7 and PSR-15 interfaces
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ResponseInterface;

// Implementations of PSR-7 and PSR-15
use Zend\Diactoros\Response\HtmlResponse;
use Zend\Diactoros\{ServerRequestFactory, Response};
use Zend\HttpHandlerRunner\Emitter\SapiEmitter;

// Create an instance of PSR-7 ServerRequestInterface object
// using Zend\Diactoros
$request = ServerRequestFactory::fromGlobals(
    $_SERVER,
    $_GET,
    $_POST,
    $_COOKIE,
    $_FILES
);

// Create a new instance of Highway\Router
$router = new Router;

// Set the handler for HTTP requests going to the root path
$router->get("/", function (ServerRequestInterface $request) {
    // Return an instance of HtmlResponse, an implementation of
    // Psr\Http\Message\ResponseInterface;
    return new HtmlResponse("It works!");
});

// Set the handler for a route with parameters
$router->get("/users/{id}/messages/{num}", function (ServerRequestInterface $request) {
    // Assign the attributes to their respective variables using the
    // getAttribute() method of Psr\Http\Message\ServerRequestInterface
    $id = $request->getAttribute("id");
    $num = $request->getAttribute("num");

    return new HtmlResponse("ID: $id NUM: $num");
});

// Get the response to the request that matches a defined route
$response = $router->match($request)->handle($request);

// Emit the response to the HTTP client
$emitter = new SapiEmitter;
$emitter->emit($response);
```

*Note: The example above assumes that URL rewrites are enabled to remove 'index.php' from the URI*

### Methods

[](#methods)

To register routes, the router can be used with the fellowing methods that correspond to their HTTP methods

```
$router->get($path, $handler);
$router->post($path, $handler);
$router->put($path, $handler);
$router->patch($path, $handler);
$router->delete($path, $handler);
$router->options($path, $handler);
```

Multiple HTTP methods can also be mapped to respond the same way. For example:

```
$router->map(["GET", "POST"], $handler);
```

### Route prefixing

[](#route-prefixing)

The router can be used to prefix routes with a given path:

```
$router->with("/users/{id}", function(Router $router) {
    // will respond to /users/{id}/likes routes
    $router->get("/likes", $likeHandler);

    // will respond to /users/{id}/friends/{fid} routes
    $router->get("/friends/{fid}", $friendHandler);
});
```

### Handlers

[](#handlers)

Handlers are passed to the router along with a route. They define actions that are dispatched when the router finds a route that matches the request.

#### Closures

[](#closures)

A handler can be defined through a closure that takes an an object implementing [PSR-7 ServerRequestInterface](https://www.php-fig.org/psr/psr-7/#321-psrhttpmessageserverrequestinterface) and returns an object implementing [PSR-7 ResponseInterface](https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface)

```
use Zend\Diactoros\Response\HtmlResponse;

$handler = function (ServerRequestInterface $request) {
    // return an instance of HtmlResponse, an implementation of
    // Psr\Http\Message\ResponseInterface;
    return new HtmlResponse("It works!");
}
```

#### PSR-15 RequestHandlerInterface

[](#psr-15-requesthandlerinterface)

A handler can be defined using an object that implements the [PSR-15 RequestHandlerInterface](https://www.php-fig.org/psr/psr-15/#21-psrhttpserverrequesthandlerinterface)

```
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Zend\Diactoros\Response\HtmlResponse;

$handler = new class implements RequestHandlerInterface {
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        return new HtmlResponse("It works!");
    }
};
```

#### Request parameters

[](#request-parameters)

Request parameters can be accessed using the `getAttribute` method of a *PSR-7 ServerRequestInterface* object:

```
$router->get("/users/{id}/messages/{num}", function (ServerRequestInterface $request) {
    $id = $request->getAttribute("id");
    /* ... */
});
```

### As a PSR-15 Middleware

[](#as-a-psr-15-middleware)

**Highway** can be used to create a PSR-15 compliant middleware. Unlike other router implementations, which themselves assign and dispatch middlewares, **Highway** itself *is* a middleware!

```
/*...*/
use Highway\{Router, RouterMiddleware};
use Zend\Diactoros\Response\HtmlResponse;
/*...*/

$routerMiddleware = RouterMiddleware::create(function (Router $router) {
    $router->get("/", function (ServerRequestInterface $request) {
        return new HtmlResponse("It works!");
    });
    /* ... */
});
```

**Highway** can then be used alongside other reusable PSR-15 middlewares. Using the [`middlewares/utils`](https://github.com/middlewares/utils#dispatcher) Dispatcher, for example:

```
/*...*/
use Middlewares\Utils\Dispatcher;
/*...*/

$routerMiddleware =  RouterMiddleware::create(function (Router $router) {
    // define routes...
});

$response = Dispatcher::run([
    $someAuthMiddleware,
    $someLoggingMiddleware,
    $routerMiddleware
]);
```

Testing
-------

[](#testing)

```
$ composer test {file or path to test}
```

Credits
-------

[](#credits)

- [Robert Narvaez](https://github.com/bobbynarvy)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

32

—

LowBetter than 69% of packages

Maintenance47

Moderate activity, may be stable

Popularity14

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

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

2810d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/12933200?v=4)[Robert Narvaez](/maintainers/bobbynarvy)[@bobbynarvy](https://github.com/bobbynarvy)

---

Top Contributors

[![bobbynarvy](https://avatars.githubusercontent.com/u/12933200?v=4)](https://github.com/bobbynarvy "bobbynarvy (24 commits)")[![fizk](https://avatars.githubusercontent.com/u/386336?v=4)](https://github.com/fizk "fizk (1 commits)")

---

Tags

psr-15psr-7routerroutinghttprouterrouting

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/bobbynarvy-highway/health.svg)

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

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.8k19.1M1.7k](/packages/cakephp-cakephp)[sunrise/http-router

A powerful solution as the foundation of your project.

17450.9k10](/packages/sunrise-http-router)[mezzio/mezzio-authentication-oauth2

OAuth2 (server) authentication middleware for Mezzio and PSR-7 applications.

28545.4k3](/packages/mezzio-mezzio-authentication-oauth2)[eliashaeussler/typo3-solver

Solver - Extends TYPO3's exception handling with AI generated solutions. Problems can also be solved from command line. Several OpenAI parameters are configurable and prompts and solution providers can be customized as desired.

302.1k](/packages/eliashaeussler-typo3-solver)

PHPackages © 2026

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