Simple PHP Routing Class

11th November 2016

Routing is an essential part of any web app or web framework which determines which code to run for a particular request. A popular approach to this is forwarding all requests to a class that deals purely with working out which code to run when by examining the url requested. Below is a very simply example of a routing class in under 20 lines of PHP code.

The Class

class NomiRouter {

    private $routes;

    public function addRoute($pattern, $function) {
        $this->routes['{'.$pattern.'}'] = $function;

    public function run() {
        foreach( $this->routes as $pattern => $function) {
            if( preg_match($pattern, $_SERVER['REQUEST_URI'], $params) ) {
                array_unshift($params, $_SERVER['REQUEST_URI']);
                return call_user_func_array($function, array_values($params));
        return false;



First you need to create an instance of the NomiRouter class. You can then add as many routes/urls as you like using the addRoute function. You pass it a regular expression as the first parameter and your function that needs to be run as the second parameter. When the code runs it'll check if the url matches any of the defined routes and then run the supplied function for that route.


$router = new NomiRouter();

$router->addRoute('^/$',function($url) {
    echo 'Welcome to the homepage';

$router->addRoute('^/articles/([0-9a-zA-Z\-]+)',function($url,$slug) {
    echo 'Displaying article with slug '.$slug;


The following is need in your .htacces file to rewrite all urls to the index.php file

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