Where should the class MyApp\Controllers\HomeController be located?
medium
A. app/Controllers/HomeController.class.php
B. app/MyApp/Controllers/HomeController.php
C. src/Controllers/HomeController.php
D. app/Controllers/HomeController.php
Solution
Step 1: Understand PSR-4 mapping
The namespace prefix "MyApp\\" maps to folder "app/". The rest of the namespace after prefix maps to subfolders.
Step 2: Map class namespace to file path
Class "MyApp\\Controllers\\HomeController" maps to "app/Controllers/HomeController.php".
Final Answer:
app/Controllers/HomeController.php -> Option D
Quick Check:
Namespace after prefix = Controllers/HomeController.php [OK]
Hint: Namespace after prefix = folder path + class name.php [OK]
Common Mistakes:
Adding namespace prefix folder again
Using wrong base folder like src/
Wrong file extension
4. You have this composer.json autoload section:
{
"autoload": {
"psr-4": {
"Lib\\": "lib/"
}
}
}
But when you try to use Lib\Utils\Helper, PHP cannot find the class. What is the likely problem?
medium
A. Composer dump-autoload was not run after adding the class
B. The class file is not located at lib/Utils/Helper.php
C. The namespace prefix "Lib\\" should not have trailing backslash
D. The folder path should be "lib\\" with double backslashes
Solution
Step 1: Check common PSR-4 issues
Folder path uses forward slashes, trailing backslash in namespace prefix is correct, so options C and D are wrong.
Step 2: Verify autoload update
After adding new classes, you must run composer dump-autoload to update the autoloader.
Final Answer:
Composer dump-autoload was not run after adding the class -> Option A
Quick Check:
Run dump-autoload after changes [OK]
Hint: Always run composer dump-autoload after adding classes [OK]
Common Mistakes:
Changing folder slashes incorrectly
Removing trailing backslash in namespace prefix
Forgetting to update autoloader
5. You want to autoload two separate namespaces in your project: "App\\": "src/",
"Vendor\\Package\\": "vendor/package/src/" Which composer.json snippet correctly sets this up?