Composer autoload

June 07, 2018

composer
php
autoloader
configuration
backend

How to create an autoloader using composer?

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

{}

to generate the autoload structure run :

$ composer install

update the composer.json file with the psr-4 specification:

{
  "autoload": {
    "psr-4": {
      "Acme\\": "src"
    }
  }
}

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

To generate the psr-4 autoload file, run the command:

$ composer dump-autoload

The content of the file will be the following one:

<?php

// 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 in src). For example if you have the class Test.php in src you could to use the something similar to this:

//Test.php
namespace Acme; //in your class called Test

class Test
{
  //code here
}

//index.php
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 this => 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/:

<?php

  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;
    }

  }

so if I want to use the previous calls in my index.php:

<?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();

That’s it!


Written by huckbit web developer who lives and works in UK building cool things. You can find me on twitter.