Composer autoloading cannot find this class
P粉403804844
P粉403804844 2024-03-26 15:07:50
0
1
435

I have a project with the following structure:

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

This is how I define psr-4 autoloading in composer.json:

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

This is my 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)
    {
    }
}

This is my ToString.php:

<?php

namespace Shop\Guitar;

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

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

This is my 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',
        };
    }
}

This is my 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);
    }
}

But when I run the test, I get the following error:

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

what is the problem? How to solve %E

P粉403804844
P粉403804844

reply all(1)
P粉764836448

This is just a question about the Composer autoloader in a PSR-4 configuration.

  • Your composer.json configuration looks legitimate.
  • require_once will not be called. This is an autoloader, and class files must not require an autoloader.

If in doubt, test your autoloader configuration.

Next steps:

  1. You can do this by changing -dassert.exception=0 to -dassert.exception=1 (0 -> 1代码> ). The test will then exit with a non-zero code (status 255 because of an uncaught exception).

    This is what you want, change -dassert.exception=0 to -dassert.exception=1 and save composer.json again.

    You can then use any Composer command that dumps the autoloader

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template