PSR-4自动装带器致命错误:找不到类 [英] PSR-4 autoloader Fatal error: Class not found
问题描述
我的项目结构如下:
src/
├─ Model/
└─ User.php
我的User.php文件如下所示:
My User.php file looks like this:
<?php
namespace Bix\Model;
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 Bix\Model\User;
// PSR-4 Autoloader.
require_once "vendor/autoload.php";
但是,如果尝试创建new User()
,则会收到错误Fatal error: Class 'User' not found in /var/www/public/api/v1/index.php on line 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
查看作曲家的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/"
,则应在src/Model/User.php
中放置一个类Bix\Model\User
.
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 Bix\Model\User
should be located in src/Model/User.php
.
编辑:您误解了PHP名称空间.在PHP中,您不是在说use Bix\Model;
将所有内容从Bix\Model
导入到此文件的全局命名空间中".而是表示:此文件中的Model
别名为Bix\Model
".
EDIT: You're misunderstanding PHP namespaces. In PHP, you're not saying "import everything from Bix\Model
into the global namespace for this file" with use Bix\Model;
. Instead, it means: "Alias Model
in this file to Bix\Model
".
所以您应该这样做:
require_once "vendor/autoload.php";
use Bix\Model;
$user = new Model\User();
或:
require_once "vendor/autoload.php";
use Bix\Model\User;
$user = new User();
这篇关于PSR-4自动装带器致命错误:找不到类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!