Skip to content

Instantly share code, notes, and snippets.

@victorknust
Forked from xeoncross/readme.md
Created January 18, 2017 11:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save victorknust/2fa2cd875d6011828d3db8d8a326bc9a to your computer and use it in GitHub Desktop.
Save victorknust/2fa2cd875d6011828d3db8d8a326bc9a to your computer and use it in GitHub Desktop.
140 byte PHP routing framework (well, it's just a function actually)

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... :(

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);}
/**
* 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);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment