Skip to content

Instantly share code, notes, and snippets.

@alixaxel
Last active December 12, 2015 01:38
Show Gist options
  • Save alixaxel/4692575 to your computer and use it in GitHub Desktop.
Save alixaxel/4692575 to your computer and use it in GitHub Desktop.
<?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;
}
<?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
Copy link

@alixaxel
Copy link
Author

@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