How to autoload classes with Composer in PHP

Composer is an essential tool for dependency management in modern PHP projects. One of its most powerful features is autoloading, which lets you automatically load classes and helper files without including them manually. In this guide, we’ll configure Composer to autoload both classes and simple PHP files using namespaces.

Define the initial project structure

Before starting, let’s define the basic file structure of the project. This will help you organize and visualize how the classes and helpers are integrated.

my-project/
├── src/
│   ├── helpers.php
│   ├── MyClass.php
├── composer.json
└── index.php

In this structure:

  • src/ will contain both namespaced classes and helper files.
  • composer.json will define the autoloading rules.
  • index.php will be the entry point to test the code.

 

Create a PHP project

  1. Create a new directory for your project and navigate to it:
    mkdir my-project
    cd my-project
    

     

  2. Initialize Composer inside the directory:
    composer init
    

    Follow the prompts to configure the composer.json  file. You can accept the default values for this tutorial.

 

Configure autoloading in composer.json

Edit the composer.json file to set up autoload rules for classes and helpers:

{
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        },
        "files": [
            "src/helpers.php"
        ]
    }
}

Here:

  • App\\ defines the main namespace.
  • src/ is the directory where your classes will be stored.
  • files allows you to include simple PHP files like helpers.

 

Create the required files

  1. Create the src/ directory:
    mkdir src
    

     

  2. Inside src/ , create the file MyClass.php:
    <?php
    
    namespace App;
    
    class MyClass {
        public function greet(string $name) {
            return "Hello, $name!";
        }
    }
    

     

  3. Also, create the helpers.php file to define common functions:
    <?php
    
    function formatMessage(string $message) {
        return strtoupper($message);
    }
    

     

Generate the autoload file

Run the following command to let Composer generate the autoload file:

composer dump-autoload

 

After this step, your project structure will look like this:

my-project/
├── src/
│   ├── helpers.php
│   ├── MyClass.php
├── vendor/
│   ├── autoload.php
│   └── composer/
├── composer.json
└── index.php

 

Use classes and helpers

Create the index.php file at the root of your project with the following content:

<?php

require __DIR__ . '/vendor/autoload.php';

use App\MyClass;

$myClass = new MyClass();
echo $myClass->greet("World") . "\n";

// Use the helper
echo formatMessage("hello world");

 

Run the file from the terminal:

php index.php

 

You should see the following output:

Hello, World!
HELLO WORLD

 

Composer greatly simplifies the process of autoloading classes and helpers in PHP. Using namespaces, PSR-4 autoloading, and included files, you can keep your project organized and scalable. Define your file structure well, experiment with this configuration, and enjoy the benefits of efficient code management.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to Top
0
Would love your thoughts, please comment.x
()
x