首頁  >  問答  >  主體

Composer 自動載入找不到該類

我有一個具有以下結構的專案:

- src
  + Guitar.php
  + Type.php
  + ToString.php
- tests
  + GuitarTest.php
composer.json

這就是我在composer.json中定義psr-4自動載入的方式:

"autoload": {
    "psr-4": {
        "Shop\Guitar\": "src/"
    }
}

這是我的 Guitar.php:

<?php

namespace Shop\Guitar;

require_once __DIR__ . '/../vendor/autoload.php';

use Shop\Guitar\Type;

class Guitar
{
    public function __construct(public readonly string $serialNumber, public readonly Type $type)
    {
    }
}

這是我的 ToString.php:

<?php

namespace Shop\Guitar;

require_once __DIR__ . '/../vendor/autoload.php';

interface ToString
{
    public function toString(): string;
}

這是我的 Type.php:

<?php

namespace Shop\Guitar;

require_once __DIR__ . '/../vendor/autoload.php';

enum Type implements ToString
{
    case ACOUSTIC;
    case ELECTRIC;

    public function toString(): string
    {
        return match($this)
        {
            self::ACOUSTIC => 'Acoustic',
            self::ELECTRIC => 'Electric',
        };
    }
}

這是我的 GuitarTest.php:

<?php

require_once __DIR__ . '/../vendor/autoload.php';

use PHPUnit\Framework\TestCase;
use Shop\Guitar\Guitar;
use Shop\Guitar\Type;

final class InventoryTest extends TestCase
{
    public function testGuitarConstructor(): void
    {
        $guitar = new Guitar('foo', Type::ELECTRIC);
    }
}

但是當我執行測試時,出現以下錯誤:

Error: Class "Shop\Guitar\Guitar" not found

問題是什麼?如何解�%B

P粉403804844P粉403804844181 天前360

全部回覆(1)我來回復

  • P粉764836448

    P粉7648364482024-03-27 12:15:40

    這只是一個關於 PSR-4 配置中的 Composer 自動載入器的問題。

    • 您的composer.json 配置看起來合法。
    • require_once 呼叫則不會。這是一個自動載入器,類別檔案一定不需要自動載入器。

    如果有疑問,請測試您的自動載入器配置。

    後續步驟:

    1. 您可以透過將-dassert.exception=0 變更為-dassert.exception=1 (0 -> <代码>1 )。然後測試將以非零代碼退出(狀態 255 因為未捕獲的異常)。

      這就是你想要的,將-dassert.exception=0 更改為-dassert.exception=1 並再次儲存composer.json .

      然後您可以使用任何轉儲自動載入器的 Composer 命%E

      回覆
      0
  • 取消回覆