You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.15 08:35:28