0
0
PHPprogramming~5 mins

PSR-4 directory mapping in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is PSR-4 in PHP?
PSR-4 is a standard for autoloading PHP classes from file paths that match their namespaces. It helps PHP find and load classes automatically based on their namespace and class name.
Click to reveal answer
beginner
How does PSR-4 map namespaces to directories?
PSR-4 maps a namespace prefix to a base directory. The namespace parts after the prefix become subdirectories inside that base directory, and the class name becomes the file name with a .php extension.
Click to reveal answer
beginner
Example: If the namespace prefix is App\ mapped to src/, where is the class App\Controllers\HomeController located?
The class App\Controllers\HomeController is located at src/Controllers/HomeController.php.
Click to reveal answer
intermediate
Why is PSR-4 preferred over older autoloading methods?
PSR-4 is preferred because it is simple, standardized, and avoids conflicts. It makes code easier to organize and share by following a clear rule to find classes based on namespaces.
Click to reveal answer
intermediate
What happens if a class file does not follow PSR-4 directory mapping?
If a class file does not follow PSR-4 mapping, the autoloader will not find the file automatically, causing errors like "class not found". You must then load the file manually or fix the directory structure.
Click to reveal answer
What does PSR-4 autoloading map to find a class file?
AFunction name to URL path
BClass name to database table
CNamespace prefix to base directory
DVariable name to environment variable
If the namespace is MyApp\Models\User and prefix MyApp\ maps to lib/, where is the class file?
Alib/User.php
Blib/MyApp/Models/User.php
CModels/User.php
Dlib/Models/User.php
What file extension does PSR-4 expect for class files?
A.php
B.txt
C.inc
D.class
What error occurs if PSR-4 mapping is incorrect?
AClass not found error
BSyntax error
CMemory overflow
DDivision by zero
Which of these is NOT a benefit of PSR-4?
AStandardized autoloading
BAutomatically compiles PHP to machine code
CSimplifies class loading
DAvoids naming conflicts
Explain how PSR-4 directory mapping works in PHP autoloading.
Think about how namespaces relate to folder paths.
You got /4 concepts.
    Describe a common error when PSR-4 directory mapping is not followed and how to fix it.
    Consider what happens if the autoloader can't find the file.
    You got /4 concepts.