【问题标题】:Composer PSR-4 Autoload class not found未找到 Composer PSR-4 自动加载类
【发布时间】:2018-06-01 09:36:38
【问题描述】:

我已经花了几个小时想弄清楚为什么自动加载对“Authentication\auth()”不起作用。 “dBase\db()”类加载得很好,但我得到了:

错误:在中找不到类 'Authentication\auth' /var/htdocs/dev/test.php 在第 8 行

调用 test.php 时。

根 composer.json -

  "require": {
    "geeshoe/dbClass": "dev-develop",
    "geeshoe/authClass": "dev-master"
  },
  "autoload": {
    "psr-4": {
      "dBase\\": "vendor/geeshoe/dbclass/",
      "Authentication\\": "vendor/geeshoe/authClass/"
    }
  }

authClass.php 头文件 -

<?php
namespace Authentication;

use dBase\db;

class auth extends db
{

test.php -

if (file_exists("vendor/autoload.php")) {
    require "vendor/autoload.php";
} else {
    echo "Dam.. Something went wrong!";
}
$test = new \dBase\db();
$var = new \Authentication\auth();

如果有人能向我指出显而易见的事情,那就太好了。附带说明一下,出于测试目的,authClass->composer.json 文件中没有指定自动加载。

【问题讨论】:

  • 1. vendor/ 中的任何内容都由作曲家创建/控制,并且应该已经定义了自己的自动加载配置。不要在composer.json 中为他们添加条目。 2. 不要在vendor/ 中创建或修改任何东西,只有作曲家自己才能接触到这个文件夹和其中的任何东西。您的代码应该位于项目文件夹中的某处else,例如:src/lib/
  • @Sammitch 谢谢你的信息。这两个类都在开发中,还没有准备好生产,因此没有在它们各自的 composer.json 文件中配置自动加载..

标签: php namespaces composer-php autoload psr-4


【解决方案1】:

这里的问题是实际上你没有使用 PSR-4。在 PSR-4 中,类名应与文件名匹配。对于db 类,它很好,因为db 类位于db.php 文件中,但auth 类位于authClass.php 文件中,这就是问题所在。您应该将文件名更新为auth.php

您可能需要运行:

composer dump-autoload

另外请记住,在实际包中,一个供应商包有一个命名空间,因此您不会为单个包创建多个命名空间,而只能为单个包创建一个

【讨论】:

  • Nabialek 谢谢,这正是我想要的。我一直认为 PSR-4 自动加载是通过命名空间而不是类名和文件名绑定的..
  • "在 PSR-4 中类名应该匹配类名"
  • @Jaxchief 谢谢,已修复。很高兴我能帮上忙
猜你喜欢
  • 2017-02-01
  • 2019-04-20
  • 1970-01-01
  • 1970-01-01
  • 2014-07-25
  • 2015-07-31
  • 2015-04-20
  • 2018-07-25
  • 2014-08-12
相关资源
最近更新 更多