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

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

pig/router
==========

A simple and lightweight PHP routing library

1.1.4(2mo ago)110MITPHPPHP &gt;=5.6.0

Since Dec 28Pushed 3w agoCompare

[ Source](https://github.com/sn01615/pig-router)[ Packagist](https://packagist.org/packages/pig/router)[ RSS](/packages/pig-router/feed)WikiDiscussions master Synced today

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

Pig Router
==========

[](#pig-router)

A simple and lightweight PHP routing library that supports HTTP methods, route grouping, middleware, and parameter handling.

**Note:** This repository includes a multilingual README. Please check other language versions for more information.

- [English](README.md)
- [中文](README_zh.md)

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

[](#installation)

Install via Composer:

```
composer require pig/router
```

Usage
-----

[](#usage)

### Basic Example

[](#basic-example)

```
$router = new \Pig\Router\Router();
try {
    $router->loadRoutes(__DIR__ . "/api.php");
    $router->dispatch();
} catch (\Pig\Router\NotFoundException $e) {
    // Handle 404
    echo "404 Not Found";
} catch (\Pig\Router\InvalidCallbackException $e) {
    echo $e->getMessage();
}
```

### Defining Routes

[](#defining-routes)

Create an `api.php` file to define your routes:

```
/**
 * @var \Pig\Router\Router $router
 */

// Simple routes
$router->get('/home', function() {
    echo "Welcome Home";
});

$router->post('/submit', [\App\Controllers\FormController::class, 'submit']);

// Routes with parameters
$router->get('/user/{id}', function($id) {
    echo "User ID: " . $id;
});

// Using regex parameters
$router->get('/user/(\d+)', function($userId) {
    echo "User ID: " . $userId;
});

// Route grouping
$router->group('/api', [], function (\Pig\Router\Router $router) {
    $router->get('/users', [\App\Controllers\UserController::class, 'index']);
    $router->post('/users', [\App\Controllers\UserController::class, 'create']);
    $router->get('/users/{id}', [\App\Controllers\UserController::class, 'show']);
});
```

### HTTP Methods

[](#http-methods)

The router supports the following HTTP methods:

- `get($pattern, $callback)`
- `post($pattern, $callback)`
- `put($pattern, $callback)`
- `delete($pattern, $callback)`
- `patch($pattern, $callback)`
- `head($pattern, $callback)`
- `options($pattern, $callback)`
- `get_post($pattern, $callback)` - Accepts both GET and POST
- `any($pattern, $callback)` - Accepts all methods

### Route Parameters

[](#route-parameters)

- Named parameters: `/user/{id}` - Captured as `$id` in the callback
- Regex parameters: `/user/(\d+)` - Captured as positional parameters

### Middleware

[](#middleware)

Add middleware to routes or groups:

```
$router->get('/admin', function() {
    echo "Admin Panel";
})->middleware([\App\Middleware\AuthMiddleware::class, 'check']);

$router->group('/admin', [\App\Middleware\AuthMiddleware::class], function ($router) {
    $router->get('/dashboard', [\App\Controllers\AdminController::class, 'dashboard']);
});
```

You can also add global before and after middleware:

```
$router->before([\App\Middleware\LoggingMiddleware::class, 'logRequest']);
$router->after([\App\Middleware\LoggingMiddleware::class, 'logResponse']);
```

Middleware can be:

- A callable function
- A class with a `handle()` method
- An array of middleware

### Route Grouping

[](#route-grouping)

Group routes with common prefixes and middleware:

```
$router->group('/api/v1', [\App\Middleware\ApiMiddleware::class], function ($router) {
    $router->get('/users', [\App\Controllers\Api\UserController::class, 'index']);
    $router->post('/users', [\App\Controllers\Api\UserController::class, 'create']);
});
```

### Callbacks

[](#callbacks)

Callbacks can be:

- Anonymous functions
- `Controller@method` strings (e.g., `'App\Controllers\UserController@index'`)
- `[Controller::class, 'method']` arrays
- Objects with a `handle()` method

### Compatible Mode

[](#compatible-mode)

For compatibility with certain frameworks or legacy code that uses a query parameter to carry the route, use `compatible_mode()` to tell the router to read the route from a specific GET key instead of parsing the request URI.

Basic usage:

```
$router->compatible_mode('r'); // Use $_GET['r'] for routing
```

Examples

- Simple web example (index.php receives ?r=/path):

```
// index.php
require __DIR__ . '/vendor/autoload.php';

$router = new \Pig\Router\Router();
$router->loadRoutes(__DIR__ . '/api.php');
$router->compatible_mode('r');

try {
    // When visiting: http://example.test/index.php?r=/home
    $router->dispatch();
} catch (\Pig\Router\NotFoundException $e) {
    echo "404 Not Found";
}
```

- Using compatible mode for frameworks or servers that forward the path into a query param (Apache/nginx rewrite):

```
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?r=/$1 [QSA,L]

```

Now requests to `/users/123` will be passed to `index.php?r=/users/123` and the router will read the path from `$_GET['r']`.

- Manual/CLI dispatch (useful for testing):

```
// Call dispatch manually with a method and path
$result = $router->dispatch('GET', '/home');
```

Compatible mode only changes how the router determines the request URI; all other features (route definitions, middleware, groups) work the same.

### Manual Dispatch

[](#manual-dispatch)

You can manually dispatch routes for testing or CLI usage:

```
$result = $router->dispatch('GET', '/home');
```

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

[](#api-reference)

### Router Class

[](#router-class)

#### Methods

[](#methods)

- `get(string $pattern, callable|array|string $callback)`: Register a GET route
- `post(string $pattern, callable|array|string $callback)`: Register a POST route
- `put(string $pattern, callable|array|string $callback)`: Register a PUT route
- `delete(string $pattern, callable|array|string $callback)`: Register a DELETE route
- `patch(string $pattern, callable|array|string $callback)`: Register a PATCH route
- `head(string $pattern, callable|array|string $callback)`: Register a HEAD route
- `options(string $pattern, callable|array|string $callback)`: Register an OPTIONS route
- `get_post(string $pattern, callable|array|string $callback)`: Register GET and POST routes
- `any(string $pattern, callable|array|string $callback)`: Register all HTTP method routes
- `group(string $prefix, array|string $middleware, callable $callback)`: Group routes
- `dispatch(string|null $method, string|null $uri)`: Dispatch the request
- `loadRoutes(string $file)`: Load routes from a file
- `compatible_mode(string $string)`: Enable compatible mode
- `before(mixed $middleware)`: Add global before middleware
- `after(mixed $middleware)`: Add global after middleware

### Route Class

[](#route-class)

#### Methods

[](#methods-1)

- `middleware(array|string $middleware)`: Add middleware to the route

### Exceptions

[](#exceptions)

- `NotFoundException`: Thrown when no route matches
- `InvalidCallbackException`: Thrown when callback is invalid
- `MethodNotFoundException`: Thrown when a method does not exist in a controller

Testing
-------

[](#testing)

The router includes a comprehensive test suite using PHPUnit.

### Running Tests

[](#running-tests)

Install dependencies and run tests:

```
composer install
composer test
```

Or run PHPUnit directly:

```
vendor/bin/phpunit
```

### Test Coverage

[](#test-coverage)

The test suite covers:

- Route registration for all HTTP methods
- Route dispatching with and without parameters
- Route grouping and middleware
- Exception handling
- Compatible mode functionality
- CLI dispatching
- Controller callbacks (array and string formats)
- Before/after middleware

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

Author
------

[](#author)

sn01615

###  Health Score

36

—

LowBetter than 79% of packages

Maintenance91

Actively maintained with recent releases

Popularity7

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity35

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

Every ~16 days

Recently: every ~0 days

Total

8

Last Release

73d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/6fd6cb8950d77fdebcef7c1cd1eac849e5610deddf19aa539f76b371ccaee152?d=identicon)[sn01615](/maintainers/sn01615)

---

Top Contributors

[![sn01615](https://avatars.githubusercontent.com/u/7794149?v=4)](https://github.com/sn01615 "sn01615 (25 commits)")

---

Tags

httpphpmiddlewarerouterrouting

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[wilaak/radix-router

High-performance radix tree based HTTP request router

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

PHPackages © 2026

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