Last active
December 12, 2015 01:38
-
-
Save alixaxel/4692575 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function RESTful($root, $convention = '_%s') | |
{ | |
$root = rtrim(str_replace('\\', '/', realpath($root)), '/'); | |
$segments = preg_replace('~/+~', '/', trim(substr($_SERVER['PHP_SELF'], strlen($_SERVER['SCRIPT_NAME'])), '/')); | |
foreach (range(0, count($segments = explode('/', $segments))) as $i) | |
{ | |
if (is_file(sprintf('%s/%s.php', $root, $path = implode('/', array_slice($segments, 0, $i)))) === true) | |
{ | |
try | |
{ | |
if (class_exists($class = sprintf($convention, basename($path, '.php')), false) !== true) | |
{ | |
require(sprintf('%s/%s.php', $root, $path)); | |
} | |
$method = new ReflectionMethod($class, strtolower($_SERVER['REQUEST_METHOD'])); | |
if (($method->isPublic() === true) && ($method->isStatic() === true)) | |
{ | |
if (count($arguments = array_slice($segments, $i)) < $method->getNumberOfRequiredParameters()) | |
{ | |
throw new Exception('Bad Request', 400); | |
} | |
exit($method->invokeArgs(null, $arguments)); | |
} | |
} | |
catch (ReflectionException $e) | |
{ | |
throw new Exception('Method Not Allowed', 405); | |
} | |
} | |
} | |
if (count($segments) > 0) | |
{ | |
throw new Exception('Not Found', 404); | |
} | |
return true; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class _posts # /rest/posts.php | |
{ | |
public static function get($id, $action = null) | |
{ | |
Dump(__METHOD__, func_get_args()); | |
} | |
public static function post($id, $action = null) | |
{ | |
Dump(__METHOD__, func_get_args()); | |
} | |
} | |
class _questions # /rest/questions.php | |
{ | |
public static function get($id = null, $slug = null) | |
{ | |
Dump(__METHOD__, func_get_args()); | |
} | |
} | |
class _ask # /rest/questions/ask.php | |
{ | |
public static function get() | |
{ | |
Dump(__METHOD__, func_get_args()); | |
} | |
public static function post() | |
{ | |
Dump(__METHOD__, func_get_args()); | |
} | |
} |
@xeoncross: That's pretty sweet. But it's still regex based...
I was hoping to address this: http://stackoverflow.com/q/14592181/89771.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You might like this micro router based on anonymous functions.