Created
October 13, 2017 11:25
-
-
Save voidnerd/e0b51344ded3809f0f24841b68865b9b 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{ | |
| public $get = []; //when get routes are defined it is save here | |
| public $post = []; // post routes are saved when when defined | |
| //make a function that defined get routes | |
| public function get($url, $controller) { | |
| $this->get[$url] = $controller; // push url and controller to get property array | |
| } | |
| //make a function that defineds post routes | |
| public function post($url, $controller) { | |
| $this->post[$url] = $controller; // push url and controller to post property array | |
| } | |
| //make a function that checks for user request method and also check of route user is trying to access exists | |
| public function processData($url, $request) { | |
| if($request === "GET") { //this checks if its a get method | |
| if(array_key_exists($url, $this->get)) { // this checks if route exists | |
| return $this->get[$url]; // if routes exist return its controller | |
| }else { | |
| return "This routes is not found, sorry"; | |
| } | |
| } else if ($request === "POST") { //this checks if its a post method | |
| if(array_key_exists($url, $this->post)) { | |
| return $this->post[$url]; // if routes exist return it's controller | |
| }else { | |
| return "This routes is not found, sorry"; | |
| } | |
| }else { | |
| return "error"; | |
| } | |
| } | |
| } | |
| // Usage | |
| //instantiate Router | |
| $app = new Router(); | |
| //define youre routes | |
| $app->get("/", "Controllers/index.controller.php"); / | |
| $app->post("about", "Controllers/index.controller.php"); | |
| $full_url = "http://{$_SERVER['HTTP_HOST']}{$_SERVER["REQUEST_URI"]}";// save current url visited by user | |
| $filtered_url = parse_url($full_url, PHP_URL_PATH); //parse the url to get the path | |
| $controller = $app->processData($filtered_url, $_SERVER["REQUEST_METHOD"]); //process request and if path exist save to controller | |
| require $controller; //require controller | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment