0
0
PHPprogramming~20 mins

PSR-4 directory mapping in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
PSR-4 Directory Mapping in PHP
📖 Scenario: You are building a simple PHP project that follows the PSR-4 standard for autoloading classes. This standard helps PHP know where to find your classes based on their namespace and class name.Imagine you have a folder called src where all your PHP classes live, and you want to set up the autoloader so PHP can automatically load your classes without you having to include files manually.
🎯 Goal: Set up a PSR-4 autoloader mapping in PHP that links the namespace MyApp\ to the src/ directory. Then, create a class inside the src/Utils folder and use the autoloader to load and instantiate it.
📋 What You'll Learn
Create an associative array called $psr4 that maps the namespace prefix 'MyApp\\' to the directory 'src/'.
Create a variable called $className with the full class name 'MyApp\\Utils\\Helper'.
Write code to convert the class name to a file path using the PSR-4 rules and store it in $filePath.
Print the value of $filePath to show the mapped file location.
💡 Why This Matters
🌍 Real World
PSR-4 autoloading is a standard used by most modern PHP projects and frameworks to load classes automatically without manual includes.
💼 Career
Understanding PSR-4 is essential for PHP developers working with frameworks like Laravel, Symfony, or Composer packages.
Progress0 / 4 steps
1
Create the PSR-4 namespace to directory mapping
Create an associative array called $psr4 that maps the namespace prefix 'MyApp\\' to the directory 'src/'.
PHP
Need a hint?

Remember to escape backslashes in PHP strings by doubling them.

2
Set the full class name to load
Create a variable called $className and set it to the string 'MyApp\\Utils\\Helper'.
PHP
Need a hint?

Use single quotes and double backslashes for namespaces.

3
Convert the class name to a file path using PSR-4 rules
Write code to convert the class name in $className to a file path using the PSR-4 rules and store it in a variable called $filePath. Use the $psr4 array to find the base directory. Replace the namespace prefix with the directory, and replace backslashes with directory separators, then add .php at the end.
PHP
Need a hint?

Use substr to remove the prefix and str_replace to change backslashes to slashes.

4
Print the mapped file path
Write a print statement to display the value of $filePath.
PHP
Need a hint?

Use print($filePath); to show the result.