Skip to content

Instantly share code, notes, and snippets.

@cameronp98
Created January 9, 2014 21:56
Show Gist options
  • Save cameronp98/8342802 to your computer and use it in GitHub Desktop.
Save cameronp98/8342802 to your computer and use it in GitHub Desktop.
Simple (crappy) PHP URI routing system
<?php
class Route {
private $_uri = [];
private $_method = [];
private function add($verb, $uri, $method) {
$this->_uri[] = ["/".trim($uri, "/"), strtoupper($verb)];
if ($method != null) {
$this->_method[] = $method;
} else {
$this->_method[] = "HomeController";
}
}
public function get($uri, $method=null) {
$this->add("GET", $uri, $method);
}
public function post($uri, $method=null) {
$this->add("POST", $uri, $method);
}
public function put($uri, $method=null) {
$this->add("PUT", $uri, $method);
}
public function delete($uri, $method=null) {
$this->add("DELETE", $uri, $method);
}
public function any($uri, $method=null) {
$this->add(".+", $uri, $method);
}
public function run() {
// extract URI and add leading backslash
$root = "/".explode("/", trim($_SERVER['SCRIPT_NAME'], "/"))[0];
$req_uri = "/".trim(str_replace($root,"",$_SERVER["REQUEST_URI"]), "/");
$req_verb = $_SERVER["REQUEST_METHOD"];
$matchFound = false;
foreach($this->_uri as $key=>$value) {
$uri = $value[0];
$verb = $value[1];
// verb AND uri match
if (preg_match("#^$verb$#", $req_verb) && preg_match("#^$uri$#", $req_uri)) {
$matchFound = true;
$method = $this->_method[$key];
if (is_string($method)) {
$className = ucfirst($method);
require_once($className.".php");
new $className();
} else {
$method();
}
}
}
// 404 error
if (!$matchFound) {
echo "<h1>404: Page not found '" . $req_uri . "'</h1>";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment