Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Last active November 1, 2017 07:57
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save xeoncross/5357205 to your computer and use it in GitHub Desktop.
Save xeoncross/5357205 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);
}
}
}
@s3rgeym
Copy link

s3rgeym commented Jul 4, 2017

function error(int $code, callable $callback = null) {
  static $callbacks = [];
  if ($callback) {
    return $callbacks[$code] = $callback;
  }
  http_response_code($code);
  if (isset($callbacks[$code])) {
    $callbacks[$code]();
  }
}


// Модифицированная версия:
function route(string $path, callable $callback = null, string $method = 'GET') {
  static $routes = [];
  if ($callback) {
    // Тут нужно поработать над перменной $path
    return $routes[$method]["#^{$path}$#"] = $callback;
  }
  $method = $_SERVER['REQUEST_METHOD'];
  if (isset($routes[$method])) {
    foreach ($routes[$method] as $pattern => $callback) {
      if (preg_match($pattern, $path, $matches)) {
        array_shift($matches);
        return $callback(...$matches);
      }
    }
  }
  error(404);
}


route('/hello/([^/]+)', function ($name) {
  echo "Hello {$name}!";
});

route('/hello/World');


error(404, function () {
  echo 'Page Not Found';
});

route('/page-no-exists');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment