0
0
PHPprogramming~30 mins

Composer autoload mechanism in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Composer autoload mechanism
📖 Scenario: You are building a simple PHP project that uses Composer to autoload classes automatically. This helps you avoid manually including each class file.
🎯 Goal: Create a PHP project with a class, configure Composer's autoload, and use the autoloaded class in your script.
📋 What You'll Learn
Create a PHP class file in the src folder
Create a composer.json file with PSR-4 autoload configuration
Run Composer to generate the autoload files
Write a PHP script that uses the autoloaded class without manual includes
💡 Why This Matters
🌍 Real World
Composer autoloading is used in almost all modern PHP projects to load classes automatically, saving time and avoiding errors from manual includes.
💼 Career
Understanding Composer autoload is essential for PHP developers working on frameworks, libraries, or any professional PHP applications.
Progress0 / 4 steps
1
Create a PHP class file
Create a folder named src and inside it create a PHP file named Greeting.php. In this file, define a class called Greeting inside the namespace App. The class should have a public method sayHello() that returns the string "Hello from Composer autoload!".
PHP
Need a hint?

Remember to declare the namespace at the top and define the class with the method returning the exact string.

2
Create composer.json with PSR-4 autoload
Create a composer.json file in your project root with a autoload section using PSR-4. Map the namespace App\\ to the src/ directory.
PHP
Need a hint?

The composer.json file must have an autoload section with psr-4 mapping App\\ to src/.

3
Run Composer to generate autoload files
Run the Composer command composer dump-autoload in your project root to generate the autoload files based on your composer.json configuration.
PHP
Need a hint?

Open your terminal and run composer dump-autoload to create the vendor/autoload.php file.

4
Use the autoloaded class in a PHP script
Create a PHP script named index.php in your project root. Include the Composer autoload file vendor/autoload.php. Then create an instance of App\Greeting and print the result of calling its sayHello() method.
PHP
Need a hint?

Use require __DIR__ . '/vendor/autoload.php'; to load Composer's autoloader. Then create new Greeting() and print the message.