PSR-4无法加载类:首个Composer包类找不到问题求助
It sounds like your Composer autoload setup isn’t properly registering your class, which is why you’re only able to get it working via manual class mapping. Let’s walk through the key fixes to get this working the right way:
1. Verify Your Package’s composer.json Autoload Configuration
Composer relies on PSR standards (most commonly PSR-4) to autoload classes automatically. Your package’s composer.json must correctly map your namespace to the source directory. Here’s a correct example setup:
{ "name": "craftsman/ez-server", "type": "library", "description": "My first Composer package", "autoload": { "psr-4": { "Craftsman\\": "src/" } }, "require": {} }
- The
psr-4entry tells Composer: "Any class under theCraftsman\namespace lives in thesrc/directory." - Double-check that the namespace prefix (
Craftsman\\) ends with a backslash, and the directory path is relative to your package’s root folder.
2. Match Your File Structure to the Namespace
Composer’s PSR-4 autoloading is case-sensitive (especially on Linux/macOS), so your file structure must exactly mirror your namespace:
- Your
EzServerclass should live insrc/EzServer.php(filename must match the class name, including case). - The top of
EzServer.phpmust declare the correct namespace:
<?php namespace Craftsman; class EzServer { public static function Hello() { return "Hello from EzServer!"; } }
3. Regenerate the Autoload Files
After updating your composer.json or file structure, run this command in your package’s root directory to refresh Composer’s autoload cache:
composer dump-autoload
This ensures Composer picks up your updated class mapping.
4. Ensure Your Usage Project Properly References the Package
If you’re testing locally (not publishing to Packagist yet), you need to tell your usage project where to find your package:
- In your usage project’s
composer.json, add a local repository entry:"repositories": [ { "type": "path", "url": "../path/to/your/craftsman-ez-server-package" } ] - Require the package with a dev version constraint:
composer require craftsman/ez-server:*@dev
5. Skip Manual Class Mapping (It’s a Temporary Band-Aid)
Manual class mapping works for a quick fix, but it defeats the purpose of Composer’s autoload system. Fixing the steps above will make the autoload work as intended without hacks.
Once you’ve completed these steps, your test code:
<?php require_once __DIR__ . "/vendor/autoload.php"; echo Craftsman\EzServer::Hello();
Should run without the "class not found" error.
内容的提问来源于stack exchange,提问作者Finlay Roelofs

