Video Lesson: Replace require statements with the Composer class autoloader in PHP

Replace require statements with the Composer class autoloader in PHP

Learn how to use Composer’s autoloader to automatically load PHP classes and eliminate manual file imports.


Lesson Content

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/"
        }
    },
    "authors": [
        {
            "name": "Mark Shust",
            "email": "[email protected]"
        }
    ],
    "require": {}
}

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);

require('vendor/autoload.php');

use App\Post;

$title = 'My Blog';
$posts = Post::getAll();
$numPosts = count($posts);
$postText = Post::getText($numPosts);
$numPostsDisplay = "$numPosts $postText";
?>
<h1><?= $title ?></h1>
<h2><?= $numPostsDisplay ?></h2>
<?php for ($i = 0; $i < $numPosts; $i++) : ?>
    <h3><?= $posts[$i]['title'] ?></h3>
    <p><?= $posts[$i]['content'] ?></p>
    <p>By <?= $posts[$i]['author'] ?></p>
<?php endfor ?>

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.

Code Diff

/vendor/

Here's the updated classes/Post.php:

<?php declare(strict_types=1);

namespace App;

class Post
{
    public static function getAll(): array
    {
        $author1 = new Author('Mark Shust');
        $author2 = new Author('Betsy Sue');

        return [
            [
                'title' => 'How to learn PHP',
                'content' => 'This is how you learn PHP.',
                'author' => $author1->getName(),
            ],
            [
                'title' => 'How to learn MySQL',
                'content' => 'This is how you learn MySQL.',
                'author' => $author1->getName(),
            ],
            [
                'title' => 'How to learn Nginx',
                'content' => 'This is how you learn Nginx.',
                'author' => $author2->getName(),
            ],
        ];
    }

    public static function getText(int $numPosts): string
    {
        return $numPosts === 1 ? 'post' : 'posts';
    }
}
Maggie

Hey, I'm Maggie! 👋

Ask me anything.

Want to chat with Maggie?

Log in for AI tutor access.

Comments

Join the discussion!

Notes

Keep track of what you learn!