PSR-4 自动加载器致命错误:找不到类 [英] PSR-4 autoloader Fatal error: Class not found

查看:27
本文介绍了PSR-4 自动加载器致命错误:找不到类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目结构如下:

src/
   ├─ Model/
      └─ User.php

我的 User.php 文件如下所示:

My User.php file looks like this:

<?php
namespace BixModel;

class User {

我的 composer.json 自动加载器是这样的:

And my composer.json autoloader is this:

"autoload": {
    "psr-4": {
      "Bix\": "src/"
    }
  }

最后我的 bootstrap.php 是这样的:

Finally my bootstrap.php is this:

use BixModelUser;

// PSR-4 Autoloader.
require_once "vendor/autoload.php";

但是,如果我尝试创建一个 new User(),我会收到错误 Fatal error: Class 'User' not found in/var/www/public/api/v1/index.php 第 8 行

However if I try and create a new User(), I get the error Fatal error: Class 'User' not found in /var/www/public/api/v1/index.php on line 8

查看 composer autoload_psr4.php 文件,它看起来不错:

Looking at the composer autoload_psr4.php file it looks ok:

//autoload_psr4.php @由 Composer 生成

// autoload_psr4.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname(dirname($vendorDir));

return array(
    'XdgBaseDir\' => array($vendorDir . '/dnoegel/php-xdg-base-dir/src'),
    'Monolog\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
    'KeenIO\' => array($vendorDir . '/keen-io/keen-io/src'),
    'Bix\' => array($baseDir . '/src'),
); 

谁能指出我上面的错误在哪里?

Can anybody point out where I am going wrong with the above?

推荐答案

首先,Linux(我不确定您使用的是哪台 PC)是区分大小写的.在您的自动加载中,您定义了 src/bix,而它是 src/Bix.

First of all, Linux (I'm not sure which PC you use) is case-sensitive. In your autoloading, you defined src/bix, while it is src/Bix.

但更重要的是,对于 PSR-4,指定的命名空间前缀包含在目录结构中(以避免目录只包含一个目录).在您的情况下,如果您配置 "Bix\": "src/",则 BixModelUser 类应位于 src/Model/User.php.

But more importantly, with PSR-4, the specified namespace prefix is not included in the directory structure (to avoid directories containing just one directory). In your case, if you configure "Bix\": "src/", a class BixModelUser should be located in src/Model/User.php.

编辑:您误解了 PHP 命名空间.在 PHP 中,您不是说将 BixModel 中的所有内容导入到此文件的全局命名空间中"与 use BixModel;.相反,它的意思是:将此文件中的Model 别名为BixModel".

EDIT: You're misunderstanding PHP namespaces. In PHP, you're not saying "import everything from BixModel into the global namespace for this file" with use BixModel;. Instead, it means: "Alias Model in this file to BixModel".

所以你应该这样做:

require_once "vendor/autoload.php";

use BixModel;

$user = new ModelUser();

或:

require_once "vendor/autoload.php";

use BixModelUser;

$user = new User();

这篇关于PSR-4 自动加载器致命错误:找不到类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆