【发布时间】:2022-12-05 19:33:04
【问题描述】:
每个人。 我已经用 PHP 创建了非常基本的路由器,但现在我被卡住了。 用户可以导航到不同的 URL 并传递可用于显示数据的参数,例如从数组中获取数据。
但是我被卡住了,我不知道如何传递这些 url 参数以便可以在文件中使用它们。
例如这条路线
"/user/:id" -> If user navigates to /user/1 -> This executes a callback function and he receives data from an array.
但是当url没有回调函数但有一个文件名时,路由器会加载一个文件,例如用户页面。
Router::get("/user/:username", "user.php");
所以我的问题是如何从路由中获取“用户名”并将其传递到 user.php 文件中?
我试过使用 $_GET['username'],但是这不起作用,因为 url 没有 ?在里面。
这是我的代码
<?php
class Router{
public static $routes = [];
public static function get($route, $callback){
self::$routes[] = [
'route' => $route,
'callback' => $callback,
'method' => 'GET'
];
}
public static function resolve(){
$path = $_SERVER['REQUEST_URI'];
$httpMethod = $_SERVER['REQUEST_METHOD'];
$methodMatch = false;
$routeMatch = false;
foreach(self::$routes as $route){
// convert urls like '/users/:uid/posts/:pid' to regular expression
$pattern = "@^" . preg_replace('/\\\:[a-zA-Z0-9\_\-]+/', '([a-zA-Z0-9\-\_]+)', preg_quote($route['route'])) . "$@D";
$matches = Array();
// check if the current request matches the expression
if(preg_match($pattern, $path, $matches) && $httpMethod === $route['method']) {
$routeMatch = true;
// remove the first match
array_shift($matches);
// call the callback with the matched positions as params
if(is_callable($route['callback'])){
call_user_func_array($route['callback'], $matches);
}else{
self::render($route['callback']);
}
}
}
if(!$routeMatch){
self::notFound();
}
}
public static function render($file, $viewsFolder='./views/'){
include($viewsFolder . $file);
}
public static function notFound(){
http_response_code(400);
include('./views/404.php');
exit();
}
}
Router::get("/", "home.php");
Router::get("/user/:id", function($val1) {
$data = array(
"Nicole",
"Sarah",
"Jinx",
"Sarai"
);
echo $data[$val1] ?? "No data";
});
Router::get("/user/:username", "user.php");
Router::get("/user/profile/:id", "admin.php");
Router::resolve();
?>
【问题讨论】:
标签: php url get router url-parameters