Simplify PHP development by using Composer to autoload classes with PSR-4 standards.
📌 What is Composer Autoloading?
Composer is a dependency manager for PHP that also provides an easy way to autoload your custom classes. Instead of manually including each file with require or include, Composer’s autoloader takes care of it automatically.
🛠️ Step 1: Install Composer
Visit getcomposer.org and follow the installation instructions for your operating system.
📁 Step 2: Create Your PHP Project
Create a new folder for your project and navigate to it in your terminal. Then run:
composer init Follow the prompts to set up your composer.json file.
🧭 Step 3: Define PSR-4 Autoloading
In your composer.json, add the following under the autoload section:
{ "autoload": { "psr-4": { "App\\": "src/" } } } This tells Composer to autoload classes in the src/ directory using the App\ namespace.
📦 Step 4: Create a Class
Create a file src/Hello.php with the following content:
<?php namespace App; class Hello { public function greet($name) { return "Hello, $name!"; } } ⚙️ Step 5: Generate Autoloader
Run the following command in your project root:
composer dump-autoload This generates the vendor/ directory and autoload.php file.
🚀 Step 6: Use Your Class
In a file like index.php, include the autoloader and use your class:
<?php require 'vendor/autoload.php'; use App\Hello; $hello = new Hello(); echo $hello->greet('World'); 🎯 Benefits of Autoloading
- No more manual
requireorincludestatements - Organized codebase with namespaces
- Faster scalability and cleaner project structure
📌 Tips for Using Composer Autoloading
- Stick to PSR-4 standards for file and namespace structure
- Use one main namespace per project for clarity
- Run
composer dump-autoloadafter adding new classes