我正在用 PHP 创建一个基本的路由器,关于如何编写普通的 PHP 路由器的在线资料并不多。所以下面是我目前的实现。基本上每个请求都被重定向到 index.php,然后它使用类路由器将用户重定向到 home.php 或 add.php。问题是如何将任何类型的变量从 index.php 传递到 home.php 或 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';
});
我的想法是我需要保存我想传递给一些全局变量的数据,如果我请求让我们说“views/home.php”home.php 将有权访问该全局变量并可以使用它。
项目文件系统:
+---php_router
| | .htaccess
| | index.php
| | notes.md
| | router.php
| |
| \---views
| add.php
| home.php