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

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

leocore/router
==============

Lightweight PHP 8.2+ routing library with pattern matching, parameter extraction, middleware support, and secure dispatching.

1.1.0(1mo ago)15↓100%MITPHPPHP ^8.2

Since Apr 7Pushed 1mo agoCompare

[ Source](https://github.com/Rocklviv/leocore-router)[ Packagist](https://packagist.org/packages/leocore/router)[ RSS](/packages/leocore-router/feed)WikiDiscussions main Synced 1mo ago

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

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

[](#php-router)

A lightweight, modern PHP 8.2+ routing library with pattern matching, parameter extraction, middleware support, and secure dispatching.

Features
--------

[](#features)

- **Pattern-based routing** with named parameters (`{id}`, `{name}`, etc.)
- **Flexible handler registration** (closures, class methods, strings)
- **Secure dispatching** with path traversal protection
- **Type-safe parameters** (int, float, bool automatic casting)
- **Built-in middleware** for CSRF protection and CORS headers
- **Secure response builder** with XSS prevention
- **PSR-4 autoloading** compatible

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

[](#installation)

Via Composer:

```
composer require leocore/router
```

Or use directly (no dependencies needed):

```
git clone https://github.com/Rocklviv/leocore-router.git
cd leocore-router
```

Usage Examples
--------------

[](#usage-examples)

### Simple closure handler

[](#simple-closure-handler)

```
use App\Router\Router;
use App\Router\Response;

$router = new Router();
$router->add('/health', fn() => new Response('OK - System Operational', 200));
```

### Handler with parameters

[](#handler-with-parameters)

```
$router->add('/users/{id}', fn(int $id) => new Response("User #{$id}", 200));
```

### Class method handler

[](#class-method-handler)

```
$router->add('/api/data/{id}', [DataHandler::class, 'getData'], ['GET', 'DELETE']);
```

### Multiple HTTP methods

[](#multiple-http-methods)

```
$router->add('/users', fn() => new Response('Users list'), ['GET']);
$router->add('/users', fn() => new Response('Create user', 201), ['POST']);
```

### Middleware example

[](#middleware-example)

```
use App\Router\Middleware\Csrf;
use App\Router\Middleware\Cors;

$router = new Router();

// Register CSRF middleware for state-changing routes
$router->add('/users', fn() => new Response('Users'), ['GET'], [
    new Csrf()
]);

// Register CORS middleware
$router->add('/api/*', fn() => new Response('API'), ['GET'], [
    new Cors(['origin' => 'https://example.com'])
]);
```

### Dispatching requests

[](#dispatching-requests)

```
$router->add('/users/{id}', fn(int $id) => new Response("User #{$id}", 200));

// Dispatch a request
$response = $router->dispatch('GET', '/users/123');
echo $response->getContent(); // Outputs: User #123
```

API Documentation
-----------------

[](#api-documentation)

### Router Class

[](#router-class)

#### `__construct()`

[](#__construct)

Initialize the router.

#### `add(string $path, callable|array|string $handler, array $methods = ['GET'], array $middleware = [])`

[](#addstring-path-callablearraystring-handler-array-methods--get-array-middleware--)

Register a new route manually.

**Parameters:**

- `$path`: Route pattern (e.g., `/users/{id}`)
- `$handler`: Closure, array of `[ClassName, method]`, or string `'ClassName::method'`
- `$methods`: Array of HTTP methods (GET, POST, PUT, etc.)
- `$middleware`: Optional array of middleware instances

#### `dispatch(string $method, string $path, ?array $headers = null): Response`

[](#dispatchstring-method-string-path-array-headers--null-response)

Dispatch a request to the matched route.

**Parameters:**

- `$method`: HTTP method (GET, POST, PUT, DELETE, PATCH, OPTIONS)
- `$path`: Request path (without query string)
- `$headers`: Optional array of headers (for CLI/testing)

**Returns:** `Response` object

#### `dumpRoutes(): array`

[](#dumproutes-array)

Get all registered routes for debugging.

**Returns:** Array of route configurations

### Middleware

[](#middleware)

#### `Csrf`

[](#csrf)

CSRF token generation and validation middleware. Returns 403 for invalid tokens.

#### `Cors`

[](#cors)

CORS header middleware with configurable origin and methods.

Security Features
-----------------

[](#security-features)

- **Path traversal protection**: Blocks `..` and null bytes in URLs
- **Method normalization**: Prevents HTTP method injection
- **CSRF protection**: Session-based token validation for state-changing operations
- **CORS control**: Configurable per-route or global CORS headers
- **XSS prevention**: `htmlspecialchars()` on all response content
- **Input sanitization**: Type casting and whitelist validation

License
-------

[](#license)

MIT License - see [LICENSE](LICENSE) file for details.

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance94

Actively maintained with recent releases

Popularity7

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity47

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

Total

2

Last Release

32d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/2eae49a0e9ccb54754631410bb1fbc70b6a6e98d58fa974fd8fda4ea647bd80b?d=identicon)[Rocklviv](/maintainers/Rocklviv)

---

Top Contributors

[![dchekirda](https://avatars.githubusercontent.com/u/165769864?v=4)](https://github.com/dchekirda "dchekirda (5 commits)")

---

Tags

httpphpmiddlewarerouterroutingPSR-4

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[hannesvdvreken/guzzle-debugbar

A Guzzle middleware that logs requests to debugbar's timeline

76410.4k1](/packages/hannesvdvreken-guzzle-debugbar)[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)
