0
0
PhpHow-ToBeginner · 3 min read

How to Use Autoload in Composer in PHP

To use autoload in Composer for PHP, define your namespaces or class directories in the composer.json file under the autoload section, then run composer dump-autoload. Finally, include vendor/autoload.php in your PHP script to automatically load classes without manual require or include statements.
📐

Syntax

The autoload section in composer.json tells Composer where to find your PHP classes. Common types include:

  • psr-4: Maps namespaces to directories.
  • classmap: Lists directories or files to scan for classes.
  • files: Lists specific files to include automatically.

After setting this, run composer dump-autoload to generate the autoload files.

In your PHP code, include vendor/autoload.php once to enable autoloading.

json
{
  "autoload": {
    "psr-4": {
      "MyApp\\": "src/"
    }
  }
}
💻

Example

This example shows how to set up PSR-4 autoloading for a namespace MyApp\ pointing to the src/ folder, then use a class without manual includes.

php
{
  "autoload": {
    "psr-4": {
      "MyApp\\": "src/"
    }
  }
}

// After saving composer.json, run in terminal:
// composer dump-autoload

// src/Hello.php
<?php
namespace MyApp;

class Hello {
    public function say() {
        return "Hello from MyApp!";
    }
}

// test.php
<?php
require __DIR__ . '/vendor/autoload.php';

use MyApp\Hello;

$greet = new Hello();
echo $greet->say();
Output
Hello from MyApp!
⚠️

Common Pitfalls

Common mistakes when using Composer autoload include:

  • Not running composer dump-autoload after changing composer.json.
  • Forgetting to include vendor/autoload.php in your PHP script.
  • Incorrect namespace or directory mapping in psr-4.
  • Using backslashes incorrectly in JSON strings (must be double escaped).

Always verify your namespace matches folder structure exactly.

php
<?php
// Wrong: forgetting to include autoload
// $obj = new MyApp\Hello(); // Fatal error: Class not found

// Right:
require __DIR__ . '/vendor/autoload.php';
$obj = new MyApp\Hello();
📊

Quick Reference

StepDescription
1Add autoload section in composer.json (usually psr-4)
2Run composer dump-autoload to generate files
3Include vendor/autoload.php in your PHP script
4Use your classes with namespaces as defined

Key Takeaways

Define namespaces and paths in composer.json under autoload (usually psr-4).
Run composer dump-autoload after any changes to composer.json.
Always include vendor/autoload.php once in your PHP scripts.
Match namespaces exactly to folder structure for autoloading to work.
Avoid manual require/include for classes managed by Composer autoload.