Created
October 24, 2019 07:07
-
-
Save lotfio/54694035a2a0e4142f100a1b9b111d1b to your computer and use it in GitHub Desktop.
PHP stupid 5 minutes router
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
class Router | |
{ | |
private $methods = array( | |
"GET", "POST", "PUT", | |
"PURGE", "DELETE" | |
); | |
private $routes; | |
public function __call($name, $arguments) | |
{ | |
if(!in_array(strtoupper($name), $this->methods)) | |
die("method " . $name . " not found !"); | |
if(!isset($arguments[0], $this->methods)) die("url is required !"); | |
if(!isset($arguments[1], $this->methods)) die("action is required !"); | |
array_unshift($arguments, $name); | |
$this->routes[] = $this->parse($arguments); | |
} | |
public function initiate() | |
{ | |
foreach($this->routes as $route) | |
{ | |
if(preg_match($route['pattern'], $_SERVER['REQUEST_URI'])) | |
{ | |
if($_SERVER['REQUEST_METHOD'] == strtoupper($route['method'])) | |
{ | |
preg_match($route['pattern'], $_SERVER['REQUEST_URI'], $m); | |
array_shift($m); | |
$route['params'] = $m; | |
if($route['action'] instanceof \Closure) | |
{ | |
$do = call_user_func($route['action'], ...$route['params']); | |
switch(gettype($do)) | |
{ | |
case "string" : echo $do; break; | |
case "array" :; | |
case "object" : echo json_encode($do); break; | |
} | |
return; | |
} | |
} | |
} | |
} | |
echo "not found"; | |
} | |
private function parse($args) | |
{ | |
$r = array(); | |
$r['method'] = strtoupper($args[0]); | |
$uri = str_replace('{', "(", $args[1]); | |
$uri = str_replace('}', ")", $uri); | |
$r['pattern'] = "~^" . $uri . "$~"; | |
$r['action'] = $args[2]; | |
$r['params'] = array(); | |
return $r; | |
} | |
public function __destruct() | |
{ | |
$this->initiate(); | |
} | |
} | |
$router = new Router; | |
$r->get("/users/{\d*}", function($id){ | |
return "hello" . $id; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment