PSR4 Composer 自动加载命名空间

2022-01-21 00:00:00 php composer-php psr-4

我一直在玩一些 Composer 自动加载,我遇到了一些问题,所以目录结构是

I've been having a little play around with some Composer autoloading and i'm getting some issues so the directory structure is

index.php
app/
   helpers/
          router.php
vendor/
   composer/
          /*usual files*/
   autoload.php

在我的 composer.json 我有以下内容

Inside my composer.json I have the following

"autoload": {
        "psr-4": {
            "App\": "app/"
        }
    }

在我的 index.php 我有

<?php
// Autoload our namespaces
require __DIR__.'/vendor/autoload.php';

use AppHelpersRouter;
$route = new Router;

得到以下错误

致命错误:在第 6 行的/var/www/public/index.php 中找不到类AppHelpersRouter"

我尝试了一些不同的方法来尝试让它工作,但我不确定我哪里出错了.这是我第一次研究在框架之外使用 Composer 进行自动加载,因此希望得到任何指导.

I have tried a few different things to try and get it working but i'm unsure where i'm going wrong. This is my first time looking into autoloading using Composer outside of a framework so would appreciate any guidance.

推荐答案

PSR-4 区分大小写.结构必须是 app/Helpers/Router.php 或大写 A 的更好的 App.

PSR-4 is case sensitive. The structure has to be app/Helpers/Router.php or better App with capital A.

必须以区分大小写的方式引用所有类名.

All class names MUST be referenced in a case-sensitive fashion.

子目录名称必须与子命名空间名称的大小写匹配.

The subdirectory name MUST match the case of the sub-namespace names.

终止类名对应于以 .php 结尾的文件名.文件名必须与终止类名的大小写匹配.

The terminating class name corresponds to a file name ending in .php. The file name MUST match the case of the terminating class name.

http://www.php-fig.org/psr/psr-4/

相关文章