A minimal routing library for PHP, inspired by Rust Axum.
⚠️ Warning: This library is in early development (pre-1.0).
APIs and behavior may change without notice. Use at your own risk.
- Fast and lightweight – minimal dependencies, small footprint.
- Flexible route matching – supports static paths, named parameters, optional segments, and wildcard routes.
- HTTP method routing – GET, POST, PUT, PATCH, DELETE, and more.
- Route nesting – prefix groups of routes cleanly.
- Fallback and 404 handling – default or path-specific fallbacks.
- Middleware support – wrap routes or all routes in a layer.
- Request state propagation – attach custom state objects to requests.
- Convenient response helpers –
json()
,text()
,redirect()
, andproblem()
responses. - Cookie and header management – structured response headers and cookies.
- View integration – simple PHP views with layout support.
- Helmet support – manage
<head>
tags programmatically. - Modern PHP 8+ syntax – typed properties, enums, union types, and match expressions.
- Composer-ready – integrates easily into existing projects.
Install via Composer:
composer require henningcullin/php-routing
All requests should be routed through a single entry point (index.php
or main.php
). Use a rewrite rule in your web server:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
location / {
try_files $uri /index.php?$query_string;
}
require_once __DIR__ . '/vendor/autoload.php';
use Routing\Router;
use Routing\Response;
use Routing\StatusCode;
// Create a router instance
$router = Router::new();
// Define routes
$router
->route('/hello/:name', Routing\get(function ($params) {
return Response::text("Hello, " . $params['name']);
}))
->route('/json', Routing\get(function () {
return Response::json(['message' => 'Hello, JSON']);
}));
// Define a fallback
$router->fallback(function () {
return Response::text("Page not found", StatusCode::NOT_FOUND);
});
// Listen for requests
$router->listen();