<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>PHP Archives - Pontis Technology</title>
	<atom:link href="https://pontistechnology.com/tag/php/feed/" rel="self" type="application/rss+xml" />
	<link>https://pontistechnology.com/tag/php/</link>
	<description></description>
	<lastBuildDate>Thu, 07 May 2026 09:55:04 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.5</generator>

<image>
	<url>https://pontistechnology.com/wp-content/uploads/2023/05/cropped-MicrosoftTeams-image-1-32x32.png</url>
	<title>PHP Archives - Pontis Technology</title>
	<link>https://pontistechnology.com/tag/php/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Build a Minimal PHP Router Class from Scratch </title>
		<link>https://pontistechnology.com/how-to-build-a-minimal-php-router-class-from-scratch/</link>
					<comments>https://pontistechnology.com/how-to-build-a-minimal-php-router-class-from-scratch/#respond</comments>
		
		<dc:creator><![CDATA[Darko Lončar]]></dc:creator>
		<pubDate>Tue, 05 May 2026 12:05:23 +0000</pubDate>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[Career]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[htaccess]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[routing]]></category>
		<category><![CDATA[URL rewriting]]></category>
		<category><![CDATA[Web Development]]></category>
		<guid isPermaLink="false">https://pontistechnology.com/?p=15862</guid>

					<description><![CDATA[<p>Not every PHP project needs a full framework. Sometimes you just need a clean way to handle a handful of API endpoints. Without pulling in Laravel or Symfony, configuration files and without a dependency manager. Just a class you can drop in and use. Over the years, working on various web applications, I’ve run into [&#8230;]</p>
<p>The post <a href="https://pontistechnology.com/how-to-build-a-minimal-php-router-class-from-scratch/">How to Build a Minimal PHP Router Class from Scratch </a> appeared first on <a href="https://pontistechnology.com">Pontis Technology</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Not every PHP project needs a full framework. Sometimes you just need a clean way to handle a handful of API endpoints. Without pulling in Laravel or Symfony, configuration files and without a dependency manager. Just a class you can drop in and use.</p>



<p class="wp-block-paragraph">Over the years, working on various web applications, I’ve run into a recurring problem: routing solutions that are either too opinionated for small projects or too bare-bones to handle dynamic URLs properly. So I built a minimal PHP router class that hits the middle ground. Clean URLs, HTTP method handling, dynamic parameters, controller dispatch, all in a single self-contained file.</p>



<p class="wp-block-paragraph">This article walks through how it works, step by step.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><em>The complete class is designed to be copied directly into any PHP project. No external dependencies, no configuration required.</em></p>
</blockquote>



<h2 class="wp-block-heading"><strong>The problem with traditional PHP URLs</strong></h2>



<p class="wp-block-paragraph">The traditional PHP approach to request handling relies on individual files per endpoint. A client calls something like:</p>



<p class="wp-block-paragraph"></p>



<pre class="wp-block-code"><code>http:&#47;&#47;www.my-simple-api-service.com/get-product-data.php?id=57</code></pre>



<p class="wp-block-paragraph">As the number of parameters grows, this becomes unmanageable &#8211; very quickly:</p>



<pre class="wp-block-code"><code>http:&#47;&#47;www.my-simple-api-service.com/get-product-data.php?id=57&amp;number_of_items=100&amp;startpage=5&amp;start_timestamp=123456...</code></pre>



<p class="wp-block-paragraph">This puts a burden on both sides of the request. The API consumer has to construct long, fragile URLs. The backend has to parse a growing list of query parameters and build increasingly complex logic around them.</p>



<p class="wp-block-paragraph">Modern frameworks solve this with URL rewriting and routing. The same request becomes:</p>



<pre class="wp-block-code"><code>http:&#47;&#47;www.my-simple-api-service.com/products/57/100/123456</code></pre>



<p class="wp-block-paragraph">The URL is cleaner, the parameters are positional, and a routing layer maps the request to the right controller method automatically.</p>



<p class="wp-block-paragraph">The mechanism behind this is URL rewriting: instead of loading a specific .php file for every request, the server redirects everything to a single entry point (typically index.php), and the router takes it from there.</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><em>You don&#8217;t always need Laravel. This guide walks through building a minimal PHP router class from scratch. One you can drop into any project with no configuration and no external dependencies.</em></p>
</blockquote>



<h2 class="wp-block-heading"><strong>Building the router class</strong></h2>



<p class="wp-block-paragraph">Here’s how the class is structured, section by section.</p>



<h3 class="wp-block-heading">1. Defining valid HTTP methods</h3>



<p class="wp-block-paragraph">The first thing the router needs to know is which HTTP methods it supports. I kept it to the four most common ones:</p>



<pre class="wp-block-code"><code>const VALID_METHODS = &#91;'GET', 'POST', 'PUT', 'DELETE'];</code></pre>



<p class="wp-block-paragraph">This constant is used later to validate incoming route definitions and reject anything unsupported early, rather than letting an invalid method cause a silent failure downstream.</p>



<h3 class="wp-block-heading">2. Storing routes</h3>



<p class="wp-block-paragraph">Routes are held in a static array on the class. Each entry stores the route string, HTTP method, controller name, action name, and the compiled regex pattern:</p>



<pre class="wp-block-code"><code>private static array $routes = &#91;];</code></pre>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Using a static array keeps the class self-contained and avoids any dependency on a database or external state.</p>



<h3 class="wp-block-heading">3. Adding routes</h3>



<p class="wp-block-paragraph">The addRoute() method is the core of route registration. It validates the HTTP method, checks that the controller action is in the expected Controller@action format, and stores the compiled route:</p>



<pre class="wp-block-code"><code>public static function addRoute(string $routeString, string $httpMethod, string $controllerAction): void

{

    if (!in_array($httpMethod, static::VALID_METHODS)) {

        throw new \InvalidArgumentException("Invalid HTTP method: $httpMethod");

    }

    if (!str_contains($controllerAction, '@')) {

        throw new \InvalidArgumentException("Invalid route action format. Expected 'Controller@method'.");

    }

    &#91;$controller, $action] = explode('@', $controllerAction, 2);

    static::$routes&#91;] = &#91;

        "routeString"    => $routeString,

        "httpMethod"     => $httpMethod,

        "controllerName" => $controller,

        "actionName"     => $action,

        "regex"          => static::compileRouteRegex($routeString),

    ];

}</code></pre>



<p class="wp-block-paragraph">Throwing exceptions on invalid input means misconfigurations surface immediately during development rather than producing unexpected behaviour in production.</p>



<h3 class="wp-block-heading"><strong>4. Helper methods for common HTTP methods</strong></h3>



<p class="wp-block-paragraph">To keep route definitions readable, the class exposes convenience methods for each HTTP verb. Instead of calling addRoute() directly, you can use:</p>



<pre class="wp-block-code"><code>public static function get(string $routeString, string $controllerAction)

{

    static::addRoute($routeString, 'GET', $controllerAction);

}

public static function post(string $routeString, string $controllerAction)

{

    static::addRoute($routeString, 'POST', $controllerAction);

}</code></pre>



<p class="wp-block-paragraph">The same pattern applies to put() and delete(). These are thin wrappers, but they make route definitions in index.php much easier to read.</p>



<h3 class="wp-block-heading"><strong>5. Handling incoming requests</strong></h3>



<p class="wp-block-paragraph">This is where the routing actually happens. The handleRequest() method normalises the incoming URI, loops through stored routes, matches against the compiled regex, and dispatches to the correct controller action:</p>



<pre class="wp-block-code"><code>public static function handleRequest(string $requestUri, string $requestHttpMethod): mixed

{

    $normalizedUri = trim($requestUri, '/');

    $normalizedUri = strtok($normalizedUri, '?') ?: '';

    foreach (self::$routes as $route) {

        if ($route&#91;'httpMethod'] !== $requestHttpMethod) continue;

        $params = static::matches($route&#91;'regex'], $normalizedUri);

        if ($params !== false) {

            foreach ($params as &amp;$param) {

                if (is_numeric($param)) $param = (int) $param;

            }

            if (!class_exists($route&#91;'controllerName'])) {

                throw new \Exception('Controller not found: ' . $route&#91;'controllerName']);

            }

            if (!method_exists($route&#91;'controllerName'], $route&#91;'actionName'])) {

                throw new \Exception("Method '{$route&#91;'actionName']}' not found in controller " . $route&#91;'controllerName']);

            }

            $controller = new($route&#91;'controllerName']);

            return $controller->{$route&#91;'actionName']}(...$params);

        }

    }

    return null; // No matching route — handle 404 externally

}</code></pre>



<p class="wp-block-paragraph">A few things worth noting here. The URI is stripped of leading/trailing slashes and query strings before matching, so the regex patterns stay simple. Numeric parameters are cast to integers automatically. If the controller class or method doesn’t exist, an exception is thrown rather than failing silently.</p>



<h3 class="wp-block-heading"><strong>6. Compiling route patterns to regex</strong></h3>



<p class="wp-block-paragraph">Dynamic route parameters like {id} need to be converted into named regex capture groups. The compileRouteRegex() method handles this:</p>



<pre class="wp-block-code"><code>private static function compileRouteRegex(string $routePattern): string

{

    $routePattern = trim($routePattern, '/');

    $parts = explode('/', $routePattern);

    $patternParts = array_map(function ($part) {

        if (preg_match('/^\{(.+?)(?::(.+?))?\}$/', $part, $matches)) {

            $paramName    = $matches&#91;1];

            $paramPattern = $matches&#91;2] ?? '&#91;a-zA-Z0-9\-\_]+';

            return "(?P&lt;$paramName>$paramPattern)";

        }

        return preg_quote($part, '/');

    }, $parts);

    return '^' . implode('/', $patternParts) . '$';

}</code></pre>



<p class="wp-block-paragraph">For example, the route /product/{id} compiles to the regex ^product/(?P&lt;id&gt;[a-zA-Z0-9\-\_]+)$. The named capture group makes it straightforward to extract the id value from the URI and pass it directly to the controller method.</p>



<h3 class="wp-block-heading"><strong>7. Matching the request URI</strong></h3>



<p class="wp-block-paragraph">The actual regex matching is handled by a separate private method that keeps handleRequest() clean:</p>



<pre class="wp-block-code"><code>private static function matches(string $routeRegex, string $requestUri): array|bool

{

    return (preg_match("~{$routeRegex}~", $requestUri, $matches))

        ? array_filter($matches, fn($key) => !is_int($key), ARRAY_FILTER_USE_KEY)

        : false;

}</code></pre>



<p class="wp-block-paragraph">If the match succeeds, only the named captures (the actual parameter values) are returned and the numeric keys from preg_match are filtered out. If there’s no match, the method returns false.</p>



<h3 class="wp-block-heading"><strong>8. Missing routes</strong></h3>



<p class="wp-block-paragraph">When no route matches, handleRequest() returns null. This keeps the router itself simple and leaves 404 handling to the application layer. For a web application that means a custom 404 page; for an API it means returning the correct HTTP response code.</p>



<h2 class="wp-block-heading"><strong>Server configuration: the .htaccess file</strong></h2>



<p class="wp-block-paragraph">The router only works if all requests are directed to index.php first. On Apache, that means a .htaccess file in the project root with URL rewriting rules:</p>



<pre class="wp-block-code"><code>RewriteEngine On

# Send all requests to index.php (skip real files and directories)

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php &#91;QSA,L]</code></pre>



<p class="wp-block-paragraph">What each rule does:</p>



<ul class="wp-block-list">
<li><strong>RewriteEngine On</strong>  enables Apache’s mod_rewrite module</li>



<li><strong>RewriteCond %{REQUEST_FILENAME} !-f</strong> skips rewriting if the request points to a real file (images, CSS, JS). These are served directly</li>



<li><strong>RewriteCond %{REQUEST_FILENAME} !-d</strong> skips rewriting if the request points to a real directory</li>



<li><strong>RewriteRule ^(.*)$ index.php [QSA,L]</strong>  rewrites everything else to index.php. The [QSA] flag preserves any query parameters; [L] marks this as the final rule</li>
</ul>



<p class="wp-block-paragraph">This is the same rewriting pattern used by Laravel, WordPress and most other PHP frameworks. If you’ve deployed any of them on Apache, this will be familiar.</p>



<h2 class="wp-block-heading"><strong>Using the router</strong></h2>



<h3 class="wp-block-heading"><strong>1. Define your routes</strong></h3>



<p class="wp-block-paragraph">In your index.php or a dedicated routes file:</p>



<pre class="wp-block-code"><code>require_once 'Router.php';

Router::get('/product/{id}',  'ProductController@show');

Router::post('/product',       'ProductController@create');

Router::put('/product/{id}',  'ProductController@update');

Router::delete('/product/{id}', 'ProductController@delete');</code></pre>



<h3 class="wp-block-heading"><strong>2. Create a controller</strong></h3>



<pre class="wp-block-code"><code>class ProductController

{

    public function show($id)

    {

        echo 'Displaying product with ID: ' . $id;

    }

    public function create()

    {

        echo 'Creating a new product.';

    }

    public function update($id)

    {

        echo 'Updating product with ID: ' . $id;

    }

    public function delete($id)

    {

        echo 'Deleting product with ID: ' . $id;

    }

}</code></pre>



<h3 class="wp-block-heading"><strong>3. Handle the incoming request</strong></h3>



<p class="wp-block-paragraph">In index.php:</p>



<pre class="wp-block-code"><code>require_once 'Router.php';

require_once 'ProductController.php';

$requestUri    = $_SERVER&#91;'REQUEST_URI'];

$requestMethod = $_SERVER&#91;'REQUEST_METHOD'];

$response = Router::handleRequest($requestUri, $requestMethod);

if ($response === null) {

    // For web: render a 404 page

    // For API: http_response_code(404); echo json_encode(&#91;'error' => 'Not found']);

    echo '404 Not Found';

}</code></pre>



<p class="wp-block-paragraph">A GET request to /product/57 will match the first route, instantiate ProductController, call show(57), and return the result.</p>



<h2 class="wp-block-heading"><strong>Strengths and limitations</strong></h2>



<h3 class="wp-block-heading"><strong>What this PHP router class does well</strong></h3>



<ul class="wp-block-list">
<li><strong>No dependencies. </strong>Copy the file into any project and it works. No Composer, no configuration, no setup</li>



<li><strong>Clean dynamic routing. </strong>Named capture groups in the regex make parameter extraction readable and reliable</li>



<li><strong>Explicit validation. </strong>Invalid HTTP methods and malformed controller actions fail loudly at route registration time, not at request time</li>



<li><strong>Easy to extend. </strong>Adding middleware support, route groups or additional HTTP methods (e.g. PATCH) requires minimal changes to the existing structure</li>
</ul>



<h2 class="wp-block-heading"><strong>Current limitations</strong> <strong>of the PHP router class</strong></h2>



<ul class="wp-block-list">
<li><strong>Integer parameters only. </strong>The automatic type casting currently handles numeric strings as integers. String parameters are passed through as-is</li>



<li><strong>Linear route matching. </strong>All routes are iterated on every request. For applications with a large number of routes, grouping routes by HTTP method (separate arrays per method) would reduce the lookup cost</li>



<li><strong>No built-in 404 handling. </strong>Returning null keeps the class flexible, but it means the application layer needs to handle missing routes explicitly. This is a deliberate trade-off, not an oversight</li>



<li><strong>Apache-specific rewriting. </strong>The provided configuration assumes Apache with mod_rewrite. Nginx requires a different approach, a location block with try_files instead of .htaccess.</li>
</ul>



<h2 class="wp-block-heading"><strong>Conclusion</strong></h2>



<p class="wp-block-paragraph">This PHP router class will not replace a full framework. It is not designed to. What it does is give you a clean, readable routing layer for projects where a framework would be excessive, like a small internal API, a lightweight microservice or a quick prototype.</p>



<p class="wp-block-paragraph">The complete class is around 80 lines. It handles dynamic routes, validates input, dispatches to controllers and stays entirely self-contained. For the right project, that’s exactly what you need.</p>



<p class="wp-block-paragraph">If you extend it with middleware support, route grouping or Nginx configuration, I’d be glad to hear how you approached it.</p>



<p class="wp-block-paragraph">Now that you&#8217;re up to speed with PHP router class, maybe you&#8217;re <a href="https://pontistechnology.com/what-are-functional-programming-building-blocks-in-php-part-1/">interested in this</a>: </p>



<figure class="wp-block-embed is-type-wp-embed is-provider-pontis-technology wp-block-embed-pontis-technology"><div class="wp-block-embed__wrapper">
<blockquote class="wp-embedded-content" data-secret="sQRtGTsFvf"><a href="https://pontistechnology.com/what-are-functional-programming-building-blocks-in-php-part-1/">What are Functional programming building blocks in PHP – Part 1</a></blockquote><iframe class="wp-embedded-content" sandbox="allow-scripts" security="restricted"  title="&#8220;What are Functional programming building blocks in PHP – Part 1&#8221; &#8212; Pontis Technology" src="https://pontistechnology.com/what-are-functional-programming-building-blocks-in-php-part-1/embed/#?secret=DXOQXYDDGh#?secret=sQRtGTsFvf" data-secret="sQRtGTsFvf" width="600" height="338" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>
</div></figure>
<p>The post <a href="https://pontistechnology.com/how-to-build-a-minimal-php-router-class-from-scratch/">How to Build a Minimal PHP Router Class from Scratch </a> appeared first on <a href="https://pontistechnology.com">Pontis Technology</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://pontistechnology.com/how-to-build-a-minimal-php-router-class-from-scratch/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/

Object Caching 69/71 objects using Memcached
Page Caching using Disk: Enhanced 
Database Caching 9/11 queries in 0.006 seconds using Memcached

Served from: pontistechnology.com @ 2026-11-27 06:28:58 by W3 Total Cache
-->