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:

<?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 just in src: So for example if you have the class Test.php in src you just need to use this.
//Test.php
namespace Acme; //in your class called Test

class Test
{

}

//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 >>> 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;
    }
}
  • 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();

huckbit

Programmer by day and mostly by night as well.