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
This is just a question about the Composer autoloader in a PSR-4 configuration.
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:
�
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 (status255
because of an uncaught exception).This is what you want, change
-dassert.exception=0
to-dassert.exception=1
and savecomposer.json
again.You can then use any Composer command that dumps the autoloader