public
Last active

140 byte PHP routing framework (well, it's just a function actually)

  • Download Gist
readme.md
Markdown

140 byte PHP routing system.

This is a very simply routing system that makes it easy to test requests to different paths. This is very limited so do not use for your applications - it's just for fun.

require('route.php');

// A user profile
route('/(\w+)/profile', function($path, $user)
{
    print "Hello " . $user;
});

// Home page
route('/', function($path)
{
    print "Hello World";
});

// Catch all fun
route('.+', function($path)
{
    print "You are at: " . $path;
});

// Run request
route(getenv('REQUEST_URI'));

Path

The first argument is the path you wish to call or save the callback for.

route($path, ....);

Callback

The second argument must be callable, so you can use

route('/', function () { /* ... */ });
route('/', 'function');
route('/', array($Object, 'method'));
route('/', array('Class', 'staticMethod'));
route('/', $Object); // Used with __invoke

HTTP RESTfulness

Sorry, in order to fit in under 140 characters I had to remove support for GET|POST|HEAD|OPTIONS|DELETE|PUT... :(

router.min.php
PHP
1
function r($p,$f=0){static$r=[];if($f)return$r[$p]=$f;foreach($r as$x=>$f)if(preg_match("~^$x$~",$p,$m))return call_user_func_array($f,$m);}
router.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/**
* Map paths to callbacks objects/closures
*
* @param string $path
* @param mixed $closure
* @return mixed
*/
function route($path, $closure = null)
{
static $routes = array();
 
if($closure) return $routes[$path] = $closure;
 
foreach($routes as $route => $closure) {
if(preg_match("~^$route$~", $path, $match)) {
return call_user_func_array($closure, $match);
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.