I am creating a basic router in PHP, there is not much online material about how to write plain PHP router. So below is my current implementation. Basically every request is redirected to index.php and it then using class router redirects user to home.php or add.php. The question is how do I pass any type of variable from index.php to home.php or add.php?
<?php
//***********************
// Router class
//*********************
class router
{
public $req = [];
public $url = "";
public $method = "";
private $url_found = false;
public function resolve($url)
{
$this->url = $url["REDIRECT_URL"];
$this->request = $url;
$this->method = $url["REQUEST_METHOD"];
}
public function get($route, $callback)
{
if ($this->method == "GET" && $this->url == $route && $this->url_found == false) {
$url_found = true;
$callback($this->req);
}
}
public function post($route, $callback)
{
if ($this->method == "POST" && $this->url == $route && $this->url_found == false) {
$url_found = true;
$callback($this->req);
}
}
}
<?php
//*******************************
// index.php
//*********************************
require './router.php';
$app = new router();
$app -> resolve($_SERVER);
$app -> get("/home", function ($req)
{
require 'views/home.php';
});
$app -> get("/add", function ($req)
{
require 'views/add.php';
});
$app -> post("/add", function ($req)
{
require 'views/home.php';
});
My idea was that i need to save data I want to pass in some global variable and if I am requesting lets say "views/home.php" home.php will have access to that global variable and can use it.
Project file system:
+---php_router
| | .htaccess
| | index.php
| | notes.md
| | router.php
| |
| \---views
| add.php
| home.php