A fast, framework-agnostic HTTP router for PHP. Define expressive routes for any HTTP method, group them by prefix, domain, port or client IP, attach middleware, inject dependencies into your handlers, generate URLs from named routes and serve static files — all on top of any PSR-7 request/response implementation.
- GET, POST, PUT, DELETE, OPTIONS, PATCH, HEAD and ANY methods (plus virtual
LINKroutes). - Optional Laravel-style method override via
$_REQUEST['_method']. - Controller handlers (
Home@about,Home::about,Home->about, or[Home::class, 'about']). - Before/after middleware (filters), per route and per controller.
- Static and dynamic route patterns, with a customizable pattern registry.
- Route grouping by prefix, domain, port and client IP.
- Named routes and URL generation.
- Reflection-based dependency injection for handlers, with optional PSR-11 container support.
- Customizable 404 handling.
- Serve files or whole directories as virtual links (with path-traversal protection).
- Optional route caching.
- PHP 8.1 or later
- Any PSR-7 HTTP message implementation and a PSR-7 emitter. The examples below use InitPHP HTTP.
- For pretty URLs, a front controller (
index.php) with URL rewriting (see below).
composer require initphp/routerThe examples in the documentation use the InitPHP HTTP library:
composer require initphp/httpApache (.htaccess):
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L]NGINX:
location / {
try_files $uri $uri/ /index.php?$query_string;
}<?php
require_once 'vendor/autoload.php';
use InitPHP\HTTP\Message\{Request, Response};
use InitPHP\HTTP\Emitter\Emitter;
use InitPHP\Router\Router;
$request = Request::createFromGlobals();
$response = new Response();
$router = new Router($request, $response);
$router->get('/', function () {
return 'Hello World!';
});
$router->post('/login', function (Request $request, Response $response) {
return $response->withStatus(401);
});
// Optional: customise the 404 response (otherwise a PageNotFoundException is thrown).
$router->setNotFoundHandler(function () {
return 'Page Not Found';
});
// Resolve the current request and build the response.
$response = $router->dispatch();
// Emit it.
(new Emitter())->emit($response);Full, example-driven documentation lives in docs/:
- Installation · Getting started · Configuration
- Routing · Route parameters & patterns · Route groups
- Controllers · Dependency injection · Middleware
- Named routes & URLs · Static file links
- Error handling · Caching
- Upgrading from 1.x to 2.0
composer test # PHPUnit
composer phpstan # static analysis (level max)
composer cs:check # coding standards (PSR-12)
composer coverage:check # line coverage with an enforced floorContributions are welcome. Please read the org-wide Contributing guide and the Code of Conduct before opening a pull request.
Released under the MIT License.