pig / router
A simple and lightweight PHP routing library
Requires
- php: >=5.6.0
Requires (Dev)
- phpunit/phpunit: ^5.7|^6.0|^7.0|^8.0|^9.0|^10.0
README
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.
Installation
Install via Composer:
composer require pig/router
Usage
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
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
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 POSTany($pattern, $callback)- Accepts all methods
Route Parameters
- Named parameters:
/user/{id}- Captured as$idin the callback - Regex parameters:
/user/(\d+)- Captured as positional parameters
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
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 can be:
- Anonymous functions
Controller@methodstrings (e.g.,'App\Controllers\UserController@index')[Controller::class, 'method']arrays- Objects with a
handle()method
Compatible Mode
For compatibility with certain frameworks:
$router->compatible_mode('r'); // Use $_GET['r'] for routing
Manual Dispatch
You can manually dispatch routes for testing or CLI usage:
$result = $router->dispatch('GET', '/home');
API Reference
Router Class
Methods
get(string $pattern, callable|array|string $callback): Register a GET routepost(string $pattern, callable|array|string $callback): Register a POST routeput(string $pattern, callable|array|string $callback): Register a PUT routedelete(string $pattern, callable|array|string $callback): Register a DELETE routepatch(string $pattern, callable|array|string $callback): Register a PATCH routehead(string $pattern, callable|array|string $callback): Register a HEAD routeoptions(string $pattern, callable|array|string $callback): Register an OPTIONS routeget_post(string $pattern, callable|array|string $callback): Register GET and POST routesany(string $pattern, callable|array|string $callback): Register all HTTP method routesgroup(string $prefix, array|string $middleware, callable $callback): Group routesdispatch(string|null $method, string|null $uri): Dispatch the requestloadRoutes(string $file): Load routes from a filecompatible_mode(string $string): Enable compatible modebefore(mixed $middleware): Add global before middlewareafter(mixed $middleware): Add global after middleware
Route Class
Methods
middleware(array|string $middleware): Add middleware to the route
Exceptions
NotFoundException: Thrown when no route matchesInvalidCallbackException: Thrown when callback is invalidMethodNotFoundException: Thrown when a method does not exist in a controller
Testing
The router includes a comprehensive test suite using PHPUnit.
Running Tests
Install dependencies and run tests:
composer install
composer test
Or run PHPUnit directly:
vendor/bin/phpunit
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
This project is licensed under the MIT License - see the LICENSE file for details.
Author
sn01615