Architecture & Design

Zero-Dependency Native PHP Router & Lightweight API Boilerplate

Framework routing engines often rely on extensive regex evaluation and dynamic dispatch trees that introduce unnecessary latency. For microservices and API backends, a native, zero-dependency PHP router delivers fast execution times and low memory footprints.

The Native Router Implementation

Below is a minimal routing class supporting HTTP verbs, dynamic route parameters, and JSON responses using pure PHP 8.x:

<?php

namespace App\Router;

class Router
{
    private array $routes = [];

    public function add(string $method, string $path, callable $handler): void
    {
        $this->routes[] = [
            'method' => strtoupper($method),
            'path' => $path,
            'handler' => $handler
        ];
    }

    public function dispatch(string $requestMethod, string $requestUri): void
    {
        $path = parse_url($requestUri, PHP_URL_PATH);

        foreach ($this->routes as $route) {
            if ($route['method'] !== $requestMethod) {
                continue;
            }

            $pattern = preg_replace('/\{([a-zA-Z0-9_]+)\}/', '(?P<$1>[^/]+)', $route['path']);
            $pattern = '#^' . $pattern . '$#';

            if (preg_match($pattern, $path, $matches)) {
                $params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
                call_user_func_array($route['handler'], $params);
                return;
            }
        }

        http_response_code(404);
        echo json_encode(['error' => 'Endpoint not found']);
    }
}

Registering Routes and Handling Requests

<?php

require_once __DIR__ . '/Router.php';

use App\Router\Router;

$router = new Router();

// Define API routes
$router->add('GET', '/api/v1/health', function() {
    header('Content-Type: application/json');
    echo json_encode(['status' => 'ok', 'timestamp' => time()]);
});

$router->add('GET', '/api/v1/users/{id}', function($id) {
    header('Content-Type: application/json');
    echo json_encode(['user_id' => (int)$id]);
});

// Dispatch request
$router->dispatch($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']);

Performance Advantages

Fast, Lightweight Engineering

Phase 1 Pixels builds custom, high-speed web infrastructure engineered for growth.