簡體   English   中英

Composer Autoload 僅在根級目錄中查找類

[英]Composer Autoload only finding classes in root-level directories

我目前正在 Slim 框架中構建一個 API,並且在找不到應該自動加載的類時遇到了一些麻煩。

文件夾結構

database
- db_connection.php

<?php
namespace Database;

class DBConnection {}

...

public
- index.php
src
- middlewares
-- authentication_middleware.php

<?php
namespace Middleware;

class AuthenticationMiddleware {}

...

- routes
-- different routes for tickets, projects, notifications etc.
- utils
-- data_convertor.php

<?php
namespace Utils;

class DataConvertor {}

...

這是我的composer.json

{
  "autoload": {
    "psr-4": {
      "Database\\": "./database",
      "Middleware\\": "./src/middlewares",
      "Utils\\": "./src/utils"
    }
  },
  "require": {
    // Dependencies
  }
}

現在,如果我src/routes進入我$db_connection = new DBConnection(); projects.php use Database\DBConnection 再往下,一切都很好,我的數據庫連接並且應用程序返回響應。 但是,既然我已經嘗試創建這些其他命名空間、中間件和實用程序,我突然收到“未捕獲的錯誤:Class“Middleware\AuthenticationMiddleware”未找到”。 它在 Slim 4 中,所以它最終的樣子如下:

<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Database\DBConnection;
use Middleware\AuthenticationMiddleware;


$app->group('/projects', function($app) {
  $app->get('', function(Request $request, Response $response, Array $args) {
    try {
      $db_connection = new DBConnection();
      // The rest of the code
    return $response->withStatus($status);
  });
})->add(new AuthenticationMiddleware()); // Here is where the "error" is generated.

我到底做錯了什么? 我已經接受了中間件可能是一個受保護的單詞的理論,因此將其更改為其他內容,但無濟於事,甚至最終將中間件重命名為 MW,將 AuthenticationMiddleware 重命名為 AM,以消除任何拼寫錯誤的機會,但同樣無濟於事。 在每一步之間,我也一直在運行composer update甚至composer dumpautoload && composer update來嘗試讓它工作。

正如標題所暗示的那樣,非加載目錄的共同點是與加載目錄不同的是, database是頂級目錄,而其他目錄則不是。 但是,只要composer.json中的路徑是正確的,那肯定沒關系?

除此之外,在發布之前進行更多谷歌搜索讓我查看了vendor/composer/autoload_psr4.php果然,它返回以下內容:

return array(
    'Utils\\' => array($baseDir . '/src/utils'),
    'Middleware\\' => array($baseDir . '/src/middlewares'),
    'Database\\' => array($baseDir . '/database'),
    // Plenty of auto-generated ones with plenty of slashes in the directory paths
)

感謝對我的問題的評論,我現在知道問題是 class 名稱,例如AuthenticationMiddleware與文件名不匹配,在這種情況下authentication_middleware.php ,通過重命名文件來改變它已經解決了問題。 奇怪的是,盡管如此,數據庫連接仍在工作-但是,嘿,現在一切正常,所以我很好!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM