Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Created September 12, 2013 22:08
Show Gist options
  • Select an option

  • Save xeoncross/6544508 to your computer and use it in GitHub Desktop.

Select an option

Save xeoncross/6544508 to your computer and use it in GitHub Desktop.
<?php
function route($method, $path, $callback) {
$pattern = '{^' . preg_replace('{:(\w+)}', '(?<\1>[^/]+)', $path) . '$}';
return function ($requiredMethod, $requiredPath) use ($pattern, $method, $callback) {
if (preg_match("{^$method$}i", $requiredMethod)
&& preg_match($pattern, $requiredPath, $matches)) {
$keys = array_filter(array_keys($matches), 'is_string');
$parameters = array_intersect_key($matches, array_flip($keys));
call_user_func_array($callback, $parameters);
return true;
}
};
}
function server($routes) {
return function ($method, $path) use ($routes) {
foreach ($routes as $route) {
if ($route($method, $path)) {
return true;
}
}
return ! print("Page not found");
};
}
$index = route('GET|POST', '/', function () {
echo "Index page!";
});
$hello = route('GET', '/:name', function ($name) {
echo "Hello $name";
});
$app = server(array($index, $hello));
$app($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment