PHP Classes

How to Use a PHP Router Library to Process HTTP Requests Using Different CallBack Functions For Each URL Using the Package Leocore Router: Route HTTP requests to callback functions

Recommend this page to a friend!
  Info   Documentation   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2026-04-07 (5 days ago) RSS 2.0 feedNot yet rated by the usersTotal: Not yet counted Not yet ranked
Version License PHP version Categories
leocore-router 1.0.0MIT/X Consortium ...8Libraries, Web services, Language, De..., P...
Description 

Author

This package can route HTTP requests to callback functions.

It provides classes that can register one or more routes specifying a URL pattern and a callback function that will be called when a request is processed that matches the given URL pattern.

The class can also take an HTTP method and a request URI to call a router callback function associated with a URL pattern that matches the current URI.

The package also supports:

- Defining routes in class attributes.

- Discovering controller class with action functions using reflection

- Middleware clases to protect against CSRF attack and issuing CORS headers

Picture of Rocklviv
  Performance   Level  
Name: Rocklviv <contact>
Classes: 2 packages by
Country: Ukraine Ukraine
Age: 40
All time rank: 239035 in Ukraine Ukraine
Week rank: 195 Up4 in Ukraine Ukraine Up

Instructions

Documentation

PHP Router

A lightweight, modern PHP 8.2+ routing library with pattern matching, parameter extraction, middleware support, and secure dispatching.

Features

  • Pattern-based routing with named parameters (`{id}`, `{name}`, etc.)
  • Flexible handler registration (closures, class methods, strings)
  • Secure dispatching with path traversal protection
  • Type-safe parameters (int, float, bool automatic casting)
  • Built-in middleware for CSRF protection and CORS headers
  • Secure response builder with XSS prevention
  • PSR-4 autoloading compatible

Installation

Via Composer:

composer require leocore/router

Or use directly (no dependencies needed):

git clone https://github.com/Rocklviv/leocore-router.git
cd leocore-router

Usage Examples

Simple closure handler

use App\Router\Router;
use App\Router\Response;

$router = new Router();
$router->add('/health', fn() => new Response('OK - System Operational', 200));

Handler with parameters

$router->add('/users/{id}', fn(int $id) => new Response("User #{$id}", 200));

Class method handler

$router->add('/api/data/{id}', [DataHandler::class, 'getData'], ['GET', 'DELETE']);

Multiple HTTP methods

$router->add('/users', fn() => new Response('Users list'), ['GET']);
$router->add('/users', fn() => new Response('Create user', 201), ['POST']);

Middleware example

use App\Router\Middleware\Csrf;
use App\Router\Middleware\Cors;

$router = new Router();

// Register CSRF middleware for state-changing routes
$router->add('/users', fn() => new Response('Users'), ['GET'], [
    new Csrf()
]);

// Register CORS middleware
$router->add('/api/*', fn() => new Response('API'), ['GET'], [
    new Cors(['origin' => 'https://example.com'])
]);

Dispatching requests

$router->add('/users/{id}', fn(int $id) => new Response("User #{$id}", 200));

// Dispatch a request
$response = $router->dispatch('GET', '/users/123');
echo $response->getContent(); // Outputs: User #123

API Documentation

Router Class

__construct()

Initialize the router.

add(string $path, callable|array|string $handler, array $methods = ['GET'], array $middleware = [])

Register a new route manually.

Parameters: - $path: Route pattern (e.g., /users/{id}) - $handler: Closure, array of [ClassName, method], or string 'ClassName::method' - $methods: Array of HTTP methods (GET, POST, PUT, etc.) - $middleware: Optional array of middleware instances

dispatch(string $method, string $path, ?array $headers = null): Response

Dispatch a request to the matched route.

Parameters: - $method: HTTP method (GET, POST, PUT, DELETE, PATCH, OPTIONS) - $path: Request path (without query string) - $headers: Optional array of headers (for CLI/testing)

Returns: Response object

dumpRoutes(): array

Get all registered routes for debugging.

Returns: Array of route configurations

Middleware

Csrf

CSRF token generation and validation middleware. Returns 403 for invalid tokens.

Cors

CORS header middleware with configurable origin and methods.

Security Features

  • Path traversal protection: Blocks `..` and null bytes in URLs
  • Method normalization: Prevents HTTP method injection
  • CSRF protection: Session-based token validation for state-changing operations
  • CORS control: Configurable per-route or global CORS headers
  • XSS prevention: `htmlspecialchars()` on all response content
  • Input sanitization: Type casting and whitelist validation

License

MIT License - see LICENSE file for details.


  Files folder image Files (14)  
File Role Description
Files folder imagepublic (1 file)
Files folder imagesrc (1 directory)
Files folder imagetests (1 directory)
Accessible without login Plain text file CLAUDE.md Data Auxiliary data
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file LICENSE Lic. License text
Accessible without login Plain text file phpunit.xml Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation

  Files folder image Files (14)  /  public  
File Role Description
  Plain text file index.php Class Class source

  Files folder image Files (14)  /  src  
File Role Description
Files folder imageRouter (2 files, 2 directories)

  Files folder image Files (14)  /  src  /  Router  
File Role Description
Files folder imageExceptions (1 file)
Files folder imageMiddleware (4 files)
  Plain text file Response.php Class Class source
  Plain text file Router.php Class Class source

  Files folder image Files (14)  /  src  /  Router  /  Exceptions  
File Role Description
  Plain text file HttpException.php Class Class source

  Files folder image Files (14)  /  src  /  Router  /  Middleware  
File Role Description
  Plain text file Auth.php Class Class source
  Plain text file Cors.php Class Class source
  Plain text file Csrf.php Class Class source
  Plain text file MiddlewareInterface.php Class Class source

  Files folder image Files (14)  /  tests  
File Role Description
Files folder imageUnit (1 file)

  Files folder image Files (14)  /  tests  /  Unit  
File Role Description
  Plain text file RouterTest.php Class Class source

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads  
 100%
Total:0
This week:0