Skip to content

Instantly share code, notes, and snippets.

@sukei
Created February 19, 2014 15:21
Show Gist options
  • Save sukei/9094158 to your computer and use it in GitHub Desktop.
Save sukei/9094158 to your computer and use it in GitHub Desktop.
A Router in a Tweet
<?php
/**
* The Router class is a fast and lightweight router (yes it is). It can handle
* a path and call the matching controller. If there is no match, then an
* exception will be throwned.
*
* ...and it fits in a tweet.
*
* @author Quentin Schuler aka Sukei <qschuler@neosyne.com>
*/
class Router{private $r;function add($r,$c){$this->r[$r]=$c;}function match($r){$r=@$this->r[$r]?:function(){throw new Exception;};$r();}}
@sukei
Copy link
Author

sukei commented Feb 19, 2014

<?php

$router = new Router();

$router->add('/hello', function() {
    echo 'Hello sukei!';
});

try {
    $router->match($_SERVER['PATH_INFO']);
} catch (Exception $e) {
    http_response_code(404);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment