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

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

lighthouse/router
=================

HTTP Router for the Lighthouse framework

v0.1.0(6mo ago)0111MITPHPPHP ^8.2CI failing

Since Dec 17Pushed 6mo agoCompare

[ Source](https://github.com/RichardTrujilloTorres/router)[ Packagist](https://packagist.org/packages/lighthouse/router)[ RSS](/packages/lighthouse-router/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (6)Versions (2)Used By (1)

Lighthouse Router
=================

[](#lighthouse-router)

A fast, simple HTTP router for the Lighthouse framework.

Installation
------------

[](#installation)

```
composer require lighthouse/router
```

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

[](#requirements)

- PHP 8.2 or higher

Features
--------

[](#features)

- Simple, expressive API
- Route parameters with `{param}` syntax
- Route groups with prefixes
- Named routes for URL generation
- Method-specific routing (GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD)
- PSR-7 request support

Quick Start
-----------

[](#quick-start)

### Basic Routing

[](#basic-routing)

```
use Lighthouse\Router\Router;

$router = new Router();

// Register routes
$router->get('/users', 'UsersController@index');
$router->post('/users', 'UsersController@store');
$router->get('/users/{id}', 'UsersController@show');
$router->put('/users/{id}', 'UsersController@update');
$router->delete('/users/{id}', 'UsersController@destroy');
```

### Route Parameters

[](#route-parameters)

Parameters are defined with curly braces and automatically extracted:

```
$router->get('/users/{id}', function ($id) {
    return "User: {$id}";
});

$router->get('/posts/{postId}/comments/{commentId}', function ($postId, $commentId) {
    return "Post {$postId}, Comment {$commentId}";
});

// Match the route
$match = $router->matchRoute('GET', '/users/123');
$match->getParameter('id'); // "123"
$match->getParameters();    // ['id' => '123']
```

### Route Groups

[](#route-groups)

Group routes with a common prefix:

```
$router->group('/api', function (Router $router) {
    $router->get('/users', 'ApiUsersController@index');
    $router->get('/posts', 'ApiPostsController@index');
});

// Creates:
// GET /api/users
// GET /api/posts
```

Nested groups:

```
$router->group('/api', function (Router $router) {
    $router->group('/v1', function (Router $router) {
        $router->get('/users', 'handler');
    });

    $router->group('/v2', function (Router $router) {
        $router->get('/users', 'handler');
    });
});

// Creates:
// GET /api/v1/users
// GET /api/v2/users
```

### Named Routes

[](#named-routes)

Name routes for URL generation:

```
$router->get('/users', 'handler')->name('users.index');
$router->get('/users/{id}', 'handler')->name('users.show');
$router->get('/users/{id}/posts/{postId}', 'handler')->name('users.posts.show');

// Generate URLs
$router->url('users.index');                           // /users
$router->url('users.show', ['id' => 123]);             // /users/123
$router->url('users.posts.show', ['id' => 1, 'postId' => 42]); // /users/1/posts/42
```

### Multiple Methods

[](#multiple-methods)

```
// Match specific methods
$router->match(['GET', 'POST'], '/form', 'FormController@handle');

// Match all methods
$router->any('/api', 'ApiController@handle');
```

### Dispatching Requests

[](#dispatching-requests)

With PSR-7 request:

```
use Lighthouse\Router\Exception\RouteNotFoundException;
use Lighthouse\Router\Exception\MethodNotAllowedException;

try {
    $match = $router->dispatch($request);

    $handler = $match->getHandler();
    $params = $match->getParameters();

    // Call your handler with parameters
} catch (RouteNotFoundException $e) {
    // 404 - Route not found
} catch (MethodNotAllowedException $e) {
    // 405 - Method not allowed
    $allowedMethods = $e->getAllowedMethods();
}
```

Or directly with method and path:

```
$match = $router->matchRoute('GET', '/users/123');
```

Exception Handling
------------------

[](#exception-handling)

### RouteNotFoundException

[](#routenotfoundexception)

Thrown when no route matches the request path:

```
catch (RouteNotFoundException $e) {
    $e->getMethod(); // "GET"
    $e->getPath();   // "/unknown"
}
```

### MethodNotAllowedException

[](#methodnotallowedexception)

Thrown when the path matches but the HTTP method doesn't:

```
catch (MethodNotAllowedException $e) {
    $e->getMethod();         // "DELETE"
    $e->getAllowedMethods(); // ["GET", "POST"]
}
```

API Reference
-------------

[](#api-reference)

### Router

[](#router)

MethodDescription`get(string $path, mixed $handler)`Register GET route`post(string $path, mixed $handler)`Register POST route`put(string $path, mixed $handler)`Register PUT route`patch(string $path, mixed $handler)`Register PATCH route`delete(string $path, mixed $handler)`Register DELETE route`options(string $path, mixed $handler)`Register OPTIONS route`head(string $path, mixed $handler)`Register HEAD route`any(string $path, mixed $handler)`Register route for all methods`match(array $methods, string $path, mixed $handler)`Register route for specific methods`group(string $prefix, callable $callback)`Create route group`dispatch(ServerRequestInterface $request)`Match PSR-7 request`matchRoute(string $method, string $path)`Match method and path`url(string $name, array $params)`Generate URL for named route`getRoutes()`Get all registered routes`clear()`Remove all routes### Route

[](#route)

MethodDescription`getMethod()`Get HTTP method`getPath()`Get route path`getHandler()`Get route handler`getName()`Get route name`name(string $name)`Set route name`getParameters()`Get extracted parameters`matches(string $method, string $path)`Check if route matches`generateUrl(array $params)`Generate URL with parameters### RouteMatch

[](#routematch)

MethodDescription`getRoute()`Get matched route`getHandler()`Get route handler`getParameters()`Get all parameters`getParameter(string $name, ?string $default)`Get single parameterTesting
-------

[](#testing)

```
composer test
```

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) for details.

Part of the Lighthouse Framework
--------------------------------

[](#part-of-the-lighthouse-framework)

This package is part of the [Lighthouse Framework](https://github.com/lighthouse-php), an educational PHP framework designed to teach how modern frameworks work internally.

###  Health Score

30

—

LowBetter than 62% of packages

Maintenance66

Regular maintenance activity

Popularity5

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity37

Early-stage or recently created project

 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

198d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/13813941?v=4)[Richard Trujillo](/maintainers/richardtrujillotorres)[@RichardTrujilloTorres](https://github.com/RichardTrujilloTorres)

---

Top Contributors

[![RichardTrujilloTorres](https://avatars.githubusercontent.com/u/13813941?v=4)](https://github.com/RichardTrujilloTorres "RichardTrujilloTorres (2 commits)")

---

Tags

httppsr-7routerroutinglighthouse

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[guzzlehttp/psr7

PSR-7 message implementation that also provides common utility methods

8.0k1.1B4.0k](/packages/guzzlehttp-psr7)[sunrise/http-router

A powerful solution as the foundation of your project.

17451.6k10](/packages/sunrise-http-router)[phpro/http-tools

HTTP tools for developing more consistent HTTP implementations.

28150.5k](/packages/phpro-http-tools)

PHPackages © 2026

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