Linux下使用PSR-4自动加载时类未找到,Windows环境正常
Hey there, let's dig into why your App\Model\DB class isn't loading on Linux when it works perfectly on Windows. This is a super common gotcha, and the root cause almost always ties back to case sensitivity—a key difference between Windows and Linux file systems. Here's how to troubleshoot and fix it step by step:
Linux treats DB.php and db.php as completely different files, but Windows ignores case differences.
- Navigate to your
App/Model/directory on the Linux server. Make sure the file is named exactlyDB.php(matching your class nameDB—capitalization and all). - Double-check the directory structure too: if your namespace is
App\Model, the corresponding directories should beapp/Model/(or whatever base path you use) with matching case. A typo likeapp/model/instead ofapp/Model/will break autoloading on Linux.
Open your project's composer.json and look at the autoload section. It should look something like this:
"autoload": { "psr-4": { "App\\": "app/" } }
- Ensure the namespace prefix (
App\\) and the directory path (app/) have matching case. For example, if your actual directory isApp/(capital A), the line should be"App\\": "App/". Linux will strictly follow this mapping to locate files.
Composer caches autoload mappings, and sometimes the Linux server needs a fresh set of these files. Run these commands in your project root on the server:
# Basic refresh composer dump-autoload # For production environments, optimize the autoloader composer dump-autoload --optimize
This regenerates files like vendor/composer/autoload_psr4.php, ensuring the latest directory and filename mappings are used.
While less likely to cause a "class not found" error, make sure the web server user (like www-data or apache) can read your DB.php file. Run these commands to set appropriate permissions:
# Make the file readable chmod 644 /path/to/your/project/App/Model/DB.php # Recursively set directory permissions to allow traversal chmod -R 755 /path/to/your/project/app/
If you're still stuck, open vendor/composer/autoload_psr4.php and find the entry for App\\. Use that path to manually construct where DB.php should live. For example, if the mapping is 'App\\' => array($baseDir . '/app'), the full path should be /path/to/project/app/Model/DB.php. Check that this exact path exists on your Linux server.
In most cases, fixing the filename/directory case mismatch and running composer dump-autoload will resolve the issue. Windows' case-insensitive file system hides these typos, but Linux won't cut you any slack!
内容的提问来源于stack exchange,提问作者GodOfNeoN

