Create Autoloader using Composer

How to create an autoloader using composer?

  • Create a new file composer.json in the main folder and insert the just curly brackets

  • Run, to generate the autoload structure :
$ composer install
        "autoload" : {
            "psr-4": {
                    "Acme\\" : "src"

Acme is a example of Company/Project name, and src is the directory that contains all the files we want include in our project.

  • Run, to generate the psr-4 autoload file, the command:
$ composer dump-autoload

The content of the file will be the following one:


// autoload_psr4.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'Acme\\' => array($baseDir . '/src'),
  • Require the file autoload.php in your main project file (e.g.: index.php):
require 'vendor/autoload.php';
  • Use namespaces Acme in your project for the file not in subfolder but just in src: So for example if you have the class Test.php in src you just need to use this.
namespace Acme; //in your class called Test

class Test


use Acme\Test; //to use the class Test

You don’t need to use src in your namespace because the autoload has the $basedir on src.

The general rule is >>> what is inside the namespace + Class Name

So for example if you have the folder User in src for the class Person:

You must have the following code structure:

Class Person.php in src/User/:


namespace Acme\User; //Use Acme + User

class Person
    protected $name;

     * @return name
    public function getName(): string
        return $this->name;

    public function setName(string $name)
        $this->name = $name;
        return $this->name;
  • index.php:

    require 'vendor/autoload.php';

    use Acme\User\Person; //Use the namespace + the class name

    $person1 = new Person();
    $person1->setName('John Doe');
    echo $person1->getName();

Composer basics

Here a basics list of Composer commands to retrieve the most used one.

Start new php project:

composer init

Install a new packages with:

composer require packageName

Use to find the exact component name

In order to get the latest versions:

composer update

Uninstall packages from composer:

composer remove packageName

Search package from composer:

composer search packageName

Shows a list of installed packages that have updates available:

composer outdated

You should always run the validate command before you commit your composer.json file:

composer validate