PHP Composer Autoload Complete Guide 2022

by Manu
PHP Composer Autoload Complete Guide 2022

Composer Autoload Complete Guide

Introduction to the Composer

Composer is a dependency manager for PHP. It allows you to manage dependencies in your PHP application. In this guide, we’ll see how to use the Composer for autoloading classes.

You need to download and install it, if have’t done it already. The official documentation link is how to download and install Composer on your computer.

To check whether the Composer installed successfully, you run the following command From terminal or cmd.

composer -v

Autoloading classes with Composer

Ok let’s see how to autoload files, Create a new file called composer.json under the project’s root folder.

In this picture, I have a file composer.json in the root folder. Don’t worry about other files main point is “composer.json” goes to root folder of your application.

Now here see the content of “composer.json”.

{
    "autoload": {
        "classmap": ["App"]
    }
}

Loading filed from “App” directory.

Incase of multiple directories do something like this

{
    "autoload": {
        "classmap": ["App","tests"]
    }
}

This will load files from multiple directories.

After adding file directories run command as given here

composer dump-autoload

Now include below given line where you want to include files using composer.

require 'vendor/autoload.php';

this autoload file is in vendor directory. This file will include all files according to “composer.json”.

Using PSR4 Composer Autoloading

Now we can do something like this as well

"autoload": {
    "psr-4": {
        "App\\":"App",
        "Tests\\": "tests"
    }
}

PSR stands for PHP Standard Recommendation.

Now Here is an important thing. “App\\” refering to a namespace. So in image above we had a directory “App”. There i have 2 files “DataController.php” and “DB.php”.

Each file has a namespace

<?php

namespace App;

class DataController
{

And

<?php

namespace App;

class DB
{

Here we are saying load file from given directories. Now each time you add new directory in composer file. you need to run “composer dump-autoload” Command

So we can see namespace “App” defined there in both files. And then we configured same namespace in “composer.json” file. for autoloading.

Now lets change the structure a bit

Here i moved the “DataController.php” inside “Controllers”. And changed its name space.

<?php

namespace App\Controllers;

class DataController
{

Still Composer will load the file as namespace “App” included in composer.json

Here is how my composer.json file looks

{
    "require-dev": {
        "phpunit/phpunit": "^9.5"
    },
    "autoload": {
        "psr-4": {
            "App\\":"App",
            "Tests\\": "tests"
        }
    }
}

Check the video guide for better understanding.