PHP MVC应用路由匹配失败返回404错误的问题排查求助
PHP MVC应用路由匹配失败返回404错误的问题排查求助
我正在开发一个MVC架构的PHP应用,但是在配置路由和控制器的环节遇到了问题——预期应该能正常调用PostController的show或index方法,结果完全没生效,还总是返回404页面。我翻来覆去检查了代码,就是找不到哪里出问题,想请各位帮忙排查一下。
以下是我的路由和请求处理代码:
<?php require __DIR__ . '/../bootstrap.php'; // Extract the path component from the full URL of the current request $request = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), "/"); $request = trim($request, "/"); $routes = [ "GET" => [ "" => ["controller" => "\app\controllers\PostController", "method" => "index"], "posts/show/([0-9]+)" => ["controller" => "\app\controllers\PostController", "method" => "show"], "admin/posts/create" => ["controller" => "app\controllers\AdminController", "method" => "create"] ], ]; $path = $request; $method = $_SERVER["REQUEST_METHOD"]; foreach ($routes[$method] as $route => $info) { $pattern = preg_replace("#/([0-9]+)#", "/([0-9]+)/", $route); if(preg_match("#^$pattern$#", $path, $matches)){ echo $matches[1]; $controller = new $info["controller"]; echo $controller; $id = $matches[1]; if($method == "POST" && $info["method"] != "delete"){ $controller->{$info["method"]}($_POST, $id); } else{ $controller->{$info["method"]}($id); } break; } } if(!isset($controller)){ http_response_code(404); require BASE_DIR . '/app/views/404.php'; exit; }
备注:内容来源于stack exchange,提问作者Nick Gatsfield
相关产品推荐
相关产品推荐

