0
0
PHPprogramming~10 mins

PSR-4 directory mapping in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define the base namespace prefix for PSR-4 autoloading.

PHP
$prefix = "[1]\\";
Drag options to blanks, or click blank then click option'
Aautoload
Bsrc
Cvendor
DApp
Attempts:
3 left
💡 Hint
Common Mistakes
Using folder names like 'src' or 'vendor' as namespace prefix.
Including backslashes in the prefix string.
2fill in blank
medium

Complete the code to map the namespace prefix to the directory path in PSR-4.

PHP
$baseDir = __DIR__ . '/[1]/';
Drag options to blanks, or click blank then click option'
Alib
Bbin
Csrc
Dapp
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'bin' or 'lib' which may not contain PHP classes.
Using absolute paths instead of relative paths.
3fill in blank
hard

Fix the error in the autoloader function to correctly replace namespace prefix with directory path.

PHP
if (strncmp($class, $prefix, [1]) !== 0) {
    return;
}
Drag options to blanks, or click blank then click option'
Astrlen($prefix)
Bstrlen($class)
Cstrpos($class, $prefix)
Dstrlen($baseDir)
Attempts:
3 left
💡 Hint
Common Mistakes
Using length of directory path instead of prefix.
Using strpos which returns position, not length.
4fill in blank
hard

Fill both blanks to correctly build the file path from the class name.

PHP
$relativeClass = substr($class, [1]);
$file = $baseDir . str_replace([2], '/', $relativeClass) . '.php';
Drag options to blanks, or click blank then click option'
Astrlen($prefix)
B'\\'
C'/'
Dstrlen($baseDir)
Attempts:
3 left
💡 Hint
Common Mistakes
Replacing forward slashes instead of backslashes.
Using length of base directory instead of prefix.
5fill in blank
hard

Fill all three blanks to complete the PSR-4 autoloader registration code.

PHP
spl_autoload_register(function ($class) {
    $prefix = '[1]\\';
    $baseDir = __DIR__ . '/[2]/';
    if (strncmp($class, $prefix, [3]) !== 0) {
        return;
    }
});
Drag options to blanks, or click blank then click option'
AApp
Bsrc
Cstrlen($prefix)
Dlib
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong directory names.
Not using the length of prefix in strncmp.