Search by

Simple url router and generator

Package info

gitlab.com/zdenekgebauer/router

pkg:composer/zdenekgebauer/router

Statistics

Installs: 14

Dependents: 1

Suggesters: 0

Stars: 0

2.0.0 2026-11-29 18:16 UTC

This package is auto-updated.

Last update: 2026-11-29 17:21:15 UTC


README

Simple PHP URL router and URL generator.

Requirements

  • PHP 8.4+
  • PSR-7 (psr/http-message ^2.0)

Installation

composer require zdenekgebauer/router

Basic usage

use ZdenekGebauer\Router\HttpMethod;
use ZdenekGebauer\Router\Route;
use ZdenekGebauer\Router\Router;

$router = new Router();

// if application is not in web root, pass the base path
$router = new Router('/some/path');

Register routes

Route handlers must return a PSR-7 ResponseInterface; invokeHandler() throws LogicException if they return anything else.

use Psr\Http\Message\ResponseInterface;

// static function
$router->addRoute(new Route('/hello', HttpMethod::GET, static function (): ResponseInterface {
    return new Response(200);
}));

// closure
$handler = function (): ResponseInterface {
    return new Response(200);
};
$router->addRoute(new Route('/closure', HttpMethod::GET, $handler));

// object method
$router->addRoute(new Route('/action', HttpMethod::GET, [$controller, 'action']));

// static method
$router->addRoute(new Route('/static', HttpMethod::GET, [MyController::class, 'action']));

Match and invoke

$route = $router->match($_SERVER['REQUEST_URI'], $_SERVER['REQUEST_METHOD']);
if ($route === null) {
    // 404
}
$response = $route->invokeHandler();

The query string is stripped before matching, so /list?page=2 matches the route /list. A trailing slash is not ignored — /list/ does not match the route /list. Normalise the URI before calling match() if you need that.

Route objects are stateful. match() stores the matched parameters in the route instance and match() returns that very instance, not a copy. getParameter() is therefore valid only until the next match() on the same route. Build the Router per request; do not share one instance across requests (RoadRunner, Swoole, FrankenPHP).

HTTP methods

HttpMethod enum is the preferred way to specify methods. String constants Route::GET etc. are kept for backwards compatibility.

// GET only (default when empty array is passed)
$router->addRoute(new Route('/page', HttpMethod::GET, $handler));

// multiple methods
$router->addRoute(new Route('/page', [HttpMethod::POST, HttpMethod::PUT], $handler));

// string constants still work
$router->addRoute(new Route('/page', Route::POST, $handler));

A route registered for GET also answers HEAD, as required by RFC 9110. Method names given as strings are upper-cased before comparison, so 'get' and 'GET' are equivalent. URIs remain case-sensitive.

Only one route can be registered per URI — GET /item and POST /item cannot coexist. Register a single route for both methods and branch inside the handler.

Route parameters

Parameters are enclosed in []. Prefix i: restricts to integers. Suffix ? marks the parameter as optional. Each parameter name may be used only once per URI; a duplicate throws InvalidArgumentException. Everything outside [] is matched literally, so ., + and other regex metacharacters are safe.

// matches /post/123 and /post/123/my-title
$router->addRoute(new Route('/post/[i:id]/[:slug]?', HttpMethod::GET,
    static function (string $id, string $slug = ''): ResponseInterface {
        // ...
    }
));

// read parameter value after match
$route = $router->match('/post/123/my-title');
$route->getParameter('id');    // '123'
$route->getParameter('slug');  // 'my-title'

Custom prefix regex:

// matches /post/2019-08-10
$route = new Route('/post/[date:from]', HttpMethod::GET, static function (string $from): ResponseInterface {
    // ...
});
$route->addPrefixRegex('date', '\d{4}-\d{2}-\d{2}');
$router->addRoute($route);

Named routes and URL generation

Pass a name as the 4th constructor argument, then use createUrl().

$router->addRoute(new Route('/post/[i:id]/[:slug]?', HttpMethod::GET, $handler, 'post_detail'));

echo $router->createUrl('post_detail', ['id' => 123, 'slug' => 'my-title']);
// → /post/123/my-title

URL generation throws InvalidArgumentException when a required parameter is missing or empty, or when a value (after rawurlencode()) would not match the route: ['id' => 'abc'] for [i:id], or a slug with a dot for [:slug]. An empty optional parameter is skipped. Values of custom prefixes are checked only on request, so a single bad value does not abort a whole batch (sitemap, feed) unless you want it to:

$route->addPrefixRegex('date', '\d{4}-\d{2}-\d{2}', validate: true);

Replacing a route

addRoute() throws LogicException when the URI or the name is already registered. Use replaceRoute() to overwrite an existing route instead. The replaced route loses its name as well; a name that belongs to a route with a different URI still throws LogicException.

$router->replaceRoute(new Route('/post/[i:id]', HttpMethod::GET, $otherHandler, 'post_detail'));

Default (catch-all) route

Matches any URI and any HTTP method. Useful as a 404 handler.

$router->addRoute(new Route(Route::DEFAULT_ROUTE_URI, [], $notFoundHandler));

Language prefix routes

LanguagePrefixRoute wraps an existing Route and prepends an optional language segment (/en/, /cs/ etc.).

use ZdenekGebauer\Router\LanguagePrefixRoute;

$inner = new Route('/article', HttpMethod::GET, $handler, 'article');
$route = new LanguagePrefixRoute(['en', 'cs'], $inner);
$router->addRoute($route);

// matches /en/article, /cs/article, and /article (no prefix)
$route = $router->match('/en/article');
$route->getParameter(LanguagePrefixRoute::PARAMETER_LANGUAGE); // 'en'

// generate URLs
$router->createUrl('article', [LanguagePrefixRoute::PARAMETER_LANGUAGE => 'cs']);
// → /cs/article

The first element of $prefixes may be an empty string to allow URLs without a language prefix as the default.

$route = new LanguagePrefixRoute(['', 'en', 'cs'], $inner);
// matches /article (no prefix), /en/article, /cs/article

Upgrading from 1.x

See CHANGELOG.md for the full list. The changes most likely to need attention:

  • PHP 8.4 or newer is required.
  • LanguagePrefixRoute wraps a route: new LanguagePrefixRoute(['en', 'cs'], new Route('/article', ...)).
  • createUri() / createUrl() throw InvalidArgumentException on a missing required parameter or on a value not matching its type, instead of returning a broken URL.
  • Router::replaceRoute() drops the name of the route it replaces.

Development

Local environment runs on Lando (Docker, PHP 8.4 + xdebug):

lando start          # start the environment
lando install        # install dependencies
lando tests          # run the test suite
lando coverage       # test suite with code coverage
lando ecs            # coding standards (lando ecs-fix to apply)
lando infection      # mutation testing, requires 100 % MSI
lando phpstan        # static analysis, level max
lando rector         # modernization dry-run (lando rector-fix to apply)

License

MIT — see LICENSE.