henningcullin/php-routing

A lightweight PHP routing library

Installs: 1

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 1

Forks: 0

Open Issues: 1

pkg:composer/henningcullin/php-routing

v0.1.0 2025-10-10 22:19 UTC

This package is auto-updated.

Last update: 2025-10-14 19:15:35 UTC


README

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.

Features

  • 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 helpersjson(), text(), redirect(), and problem() 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.

Installation

Install via Composer:

composer require henningcullin/php-routing

Setup

All requests should be routed through a single entry point (index.php or main.php). Use a rewrite rule in your web server:

Apache .htaccess example

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

Nginx example

location / {
   try_files $uri /index.php?$query_string;
}

Example Usage

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();