PSR-4 autoload PHP classes

User
What is composer 4 psr autoload
How to use in core php to create classes
Assistant
### ✅ What is `composer` PSR-4 Autoloading?

**PSR-4** is a PHP-FIG standard that defines how class files should be autoloaded based on their namespace. It allows you to automatically load classes without manually including files.

Composer supports PSR-4 autoloading out of the box. You define a namespace prefix and the directory that contains the class files.

### ✅ Basic Folder Structure (Core PHP Example)

Suppose you have the following structure:

myapp/
│
├── composer.json
├── index.php
└── src/
    └── App/
        └── Hello.php

### ✅ Step-by-Step: Setup Composer with PSR-4

#### 1. Initialize Composer

If you haven’t already:

composer init

Follow prompts, or skip by creating `composer.json` manually.

#### 2. Define PSR-4 Autoload in `composer.json`

{
  "autoload": {
    "psr-4": {
      "App\": "src/App/"
    }
  }
}

> `"App\"` is the namespace prefix, and `src/App/` is the directory where the class files are located.

#### 3. Create a Class

`src/App/Hello.php`:

<?php

namespace App;

class Hello {
    public function greet() {
        return "Hello from App\Hello class!";
    }
}

#### 4. Run Composer Dump-Autoload

After setting up `composer.json`, run:

composer dump-autoload

This generates the `vendor/autoload.php` file.

#### 5. Use the Class in Your Core PHP File

`index.php`:

<?php

require __DIR__ . '/vendor/autoload.php';

use AppHello;

$hello = new Hello();
echo $hello->greet();

### ✅ Output:

Hello from AppHello class!

### ✅ Summary

| Step | Description |
|——|————-|
| `composer init` | Initializes your project |
| `"autoload": { "psr-4": { "App\": "src/App/" } }` | Registers namespace with Composer |
| `composer dump-autoload` | Generates the autoloader |
| `require 'vendor/autoload.php'` | Loads all registered classes |
| `use AppYourClass;` | Imports your class using namespace |

Let me know if you want to organize it for multiple modules, or need DI-style bootstrapping!

Leave a Comment

Your email address will not be published. Required fields are marked *