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

PHP AltoRouter命名空间问题:控制器类无法被找到

PHP AltoRouter 控制器类无法通过命名空间自动加载的问题解决

问题场景

使用AltoRouter时,已配置PSR-4自动加载规则,但控制器类始终无法被自动检测到;手动引入类文件可正常运行,执行composer dump-autoload也无效。

相关代码

composer.json

{
    "require": {
        "altorouter/altorouter": "^2.0.1"
    },
    "autoload": {
        "psr-4": {
            "Controllers\\": "/controllers"
        }
    }
}

router.php

<?php
require_once 'vendor/autoload.php';

use AltoRouter as Router;
use Controllers\MentionsLegalesController as MentionsLegalesController;

// 初始化路由
$router = new Router();

// 定义路由
$router->map('GET', '/refonte_site/mentions-legales', function () {
    $controller = new MentionsLegalesController();
    $controller->index();
}, 'mentions-legales');

// 匹配当前路由
$match = $router->match();

// 如果找到路由,调用关联类的方法
if ($match && is_callable($match['target'])) {
    call_user_func($match['target']);
} else {
    // 如果未找到路由,返回404错误
    header("HTTP/1.0 404 Not Found");
    echo '404 Not Found';
    echo '请求路径:' . $_SERVER['REQUEST_URI'];
    var_dump($match);
}

/controllers/MentionsLegalesController.php

<?php 

namespace Controllers;

class MentionsLegalesController {
    public function index() {
        // 法律声明页面逻辑
        include __DIR__ . '/../views/mentions-legales.php';
    }
}

报错信息

Fatal error: Uncaught Error: Class "Controllers\MentionsLegalesController" not found in C:\wamp64\www\refonte_site\router.php on line 17
Error: Class "Controllers\MentionsLegalesController" not found in C:\wamp64\www\refonte_site\router.php on line 17

解决方法

修改composer.json中的PSR-4路径配置,将绝对路径前缀/controllers改为相对路径controllers:

{
    "require": {
        "altorouter/altorouter": "^2.0.1"
    },
    "autoload": {
        "psr-4": {
            "Controllers\\": "controllers"
        }
    }
}

修改后重新执行composer dump-autoload即可生效。

原因分析

Composer的PSR-4自动加载规则中,路径配置需使用相对路径(相对于项目根目录),而非绝对路径。配置/controllers会被解析为系统根目录下的controllers文件夹,而非当前项目根目录下的对应文件夹,导致自动加载器无法定位到正确的类文件路径。

内容的提问来源于stack exchange,提问作者rindak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 21:17:20