Autoloading PHP Classes the Composer Way

Learn about autoloading our own classes as well as other non-Packagist classes with the Composer autoloader.

Autoloading allows us to use PHP classes without the need to require or include them and is considered a hallmark of modern programming.

Autoloading Packagist code libraries

Previously, we saw that all it takes to autoload Packagist libraries is to add the following line (at the top of our scripts) that requires the Composer built-in autoloader:

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

However, when we’re working with our own classes (or with non-Packagist classes), we may need to be somewhat more savvy.

Composer autoloading can work in two main ways—through direct autoloading of classes or through PHP Standard Recommendation (PSR) standards.

Autoloading classes with the composer

The simplest way is to autoload each class separately. For this purpose, all we need to do is define the array of paths to the classes that we want to autoload in the composer.json file. For example:

{ 
   "autoload": { 
      "classmap": [
           "path/to/FirstClass.php",
           "path/to/SecondClass.php"
      ] 
   } 
}

Update the composer autoloader from the command-line:

$ php composer.phar dump-autoload -o

Now, we have to include the autoloader at the top of our scripts (for example, index.php):

<?php
require "vendor/autoload.php";

We can autoload directories that contain classes in the same way that we autoload classes by using the classmap key of the autoload:

{ 
   "autoload": { 
      "classmap": [
           "path/to/FirstClass.php",
           "path/to/directory"
      ] 
   } 
}

To autoload directories, we need to use namespaces.

As we can see, classmap autoloading is not much different than the long list of requires that we used in older PHP scripts. A better way to autoload is by using the PSR-4 standard.

Autoloading with PSR-4

PSR-4 is the newest standard of autoloading in PHP. It compels us to use namespaces. We need to take the following steps in order to autoload our classes with PSR-4:

  • Put the classes that we want to autoload in a dedicated directory. For example, it is customary to convene the classes that we write into a directory called src/.

  • Give the classes a namespace. We must give all the classes in the src/ directory the same namespace. For example, let’s give the namespace Acme to the classes. This is what the Page class is going to look like:

Get hands-on with 1400+ tech skills courses.