Replace PHP require statements with the Composer class autoloader

We are still manually importing files & classes all around our code, but this isn’t a common practice in modern PHP development once you start working with classes. It would be very cumbersome to manage, and hard-coded file paths will make your app a bit tough to maintain.

Instead, you can use a PHP autoloader. It’s common to use Composer’s dump-autoload functionality to do this.

Let’s remove all of the require statements from our code. Instead, we will use Composer’s class autoloader to automatically include these classes for us.

First, instantiate; a Composer configuration file if you don’t already have a composer.json file in the root of your project. You can do this with

composer init

You’ll have a lot of prompts come up. Let’s just accept all of the defaults. At the time of this lesson, you’ll need to hit enter 13 times. Yup.

After that is done, we need to modify our composer.json file. Open it up. And we need to map our App namespace to the classes directory. So lets update this file to read:

    "name": "markshust/myphp",
    "autoload": {
        "psr-4": {
            "App\\\\": "classes/"

After this update is done, we need Composer to register all of these classes with the autoloader. This is very easy with command line — all we need to do is run

composer dump-autoload

One last step is to include the generated Composer autoload file. Add it to start of index.php file with:

<?php declare(strict_types=1);


This is really the only file we need to require! The autoloader handles all of the other class imports for us.

Now when we reload the page, all of the referenced classes are automatically imported for us, so we just need to include classes with the use statement, and the autoloader handles everything else for us. You may need to periodically run the composer dump-autoload command when new root namespaces are added to your codebase.

Complete and Continue  
Extra lesson content locked
Enroll to access source code, comments & track progress.
Enroll for Free to Unlock