PHP Nano-Router

Custom routers were all-the-rage a few months ago but I’m afraid I missed the boat, so here’s my so-small-it’s-not-really-a-router router.

See the git repo

You’ll need 3 files:

  1. .htaccess
  2. router.php
  3. index.php

Show me the code

Put the following in .htaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

then this in router.php:

<?php return explode('/', trim($_SERVER['QUERY_STRING'], '/'));

finally, this in index.php:

<?php $r = require 'router.php';

To what end?

Admittedly, this isn’t technically a router because it doesn’t map requests to code — but you can do that yourself with simple ifs and switches:

// Get user info
if ($r[0] === 'user' && is_int($r[1])) new User($r[1]);

// Render a static page
elseif (in_array($r[0] ['about', 'contact']) new Page($r[0]);

// Call an API
elseif ($r[0] === 'api' && $_SERVER['REQUEST_METHOD'] === 'POST') {
$api = new API($r);
echo $api->getJson();
}

// Throw 404
else new Page(404);

It won’t win any awards, but hopefully demonstrates that routers don’t have to be half-megabyte behemoths that do everything but “Tea; Earl Grey; Hot”. When you remove all the syntactical sugar, validation, type-checking and whatnot, what you’re left with is the ability to say “For a request like this, do that”.

Primitive: yes. Ugly: very. Useful in production: absolutely not. Hackathon boilerplate: affirmative.

Leave a Reply

Your email address will not be published.