Last active
November 26, 2021 16:32
-
-
Save john555/ef2cbaa017e6bebf9ea0ee46343964d8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Router | |
{ | |
private $request; | |
private $supportedHttpMethods = array( | |
"GET", | |
"POST" | |
); | |
function __construct(IRequest $request) | |
{ | |
$this->request = $request; | |
} | |
function __call($name, $args) | |
{ | |
list($route, $method) = $args; | |
if(!in_array(strtoupper($name), $this->supportedHttpMethods)) | |
{ | |
$this->invalidMethodHandler(); | |
} | |
$this->{strtolower($name)}[$this->formatRoute($route)] = $method; | |
} | |
/** | |
* Removes trailing forward slashes from the right of the route. | |
* @param route (string) | |
*/ | |
private function formatRoute($route) | |
{ | |
$result = rtrim($route, '/'); | |
if ($result === '') | |
{ | |
return '/'; | |
} | |
return $result; | |
} | |
private function invalidMethodHandler() | |
{ | |
header("{$this->request->serverProtocol} 405 Method Not Allowed"); | |
} | |
private function defaultRequestHandler() | |
{ | |
header("{$this->request->serverProtocol} 404 Not Found"); | |
} | |
/** | |
* Resolves a route | |
*/ | |
function resolve() | |
{ | |
$methodDictionary = $this->{strtolower($this->request->requestMethod)}; | |
$formatedRoute = $this->formatRoute($this->request->requestUri); | |
$method = $methodDictionary[$formatedRoute]; | |
if(is_null($method)) | |
{ | |
$this->defaultRequestHandler(); | |
return; | |
} | |
echo call_user_func_array($method, array($this->request)); | |
} | |
function __destruct() | |
{ | |
$this->resolve(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to make the router dynamic?