PHP autoloading classes example with namespaces

A post on why and how to do file autoloading and namespaces in PHP 7.4 plus.

Autoloading files cleans up the code, you no longer have to spam a potential list of includes/requires at the beginning of all your files, this makes maintaining the code better when it is isn’t a structured mess.

The bad method:

include('classes/backend/db.php');
include('classes/backend/users.php');
include('classes/backend/products.php');
include('classes/backend/helpers.php');
include('classes/frontend/html.php');
include('classes/frontend/styling.php');

Whilst using the autoload feature seems more work than to just doing an include to one file which branches of to many, the idea is when working in a large project autoloading is simple and hassle-free.

php autoload classes

The use of namespaces helps the organisation and importantly avoid function name collisions, they are very critical if your project is open-sourced + composer compatible.

Layout

This blog post autoloading example is structured as:

classes/
-------autoload.php
-------backend/
---------------users.php
-------frontend/
----------------html.php
----------------style.php
index.php

The root has an index.php file and the classes/ directory which contains the backend/ and frontend/ directory along with autoload.php file.

Inside classes/backend/ is users.php and inside classes/frontend/ is html.php and style.php.

The files

index.php:

<?php
require(__DIR__ . '/classes/autoload.php');

use backend\users;
use frontend\html;
use frontend\style;

$html = new html();
$html->tagOpen('head');//<head>

$user = new users(1, 'Gary', 'Bilbo');
$user_name = $user->userName();//Gary Bilbo

$html->pageTitle($user_name);//<title>Gary Bilbo</title>
$style = new style();//<style>body{background-color:#b5cde5;};</style>

$html->tagClose('head');//</head>

echo $user->userId();//1

autoload.php:

<?php
spl_autoload_register(function ($className) {
    $filename = __DIR__ . DIRECTORY_SEPARATOR . str_replace('\\', '/', $className) . '.php';
    if (file_exists($filename)) require_once($filename);
});

spl_autoload_register() is the inbuilt PHP function that is used to create a queue to process through and autoload files.

autoload.php is the file that gets included (required) in each of your working files.

classes/backend/users.php:

<?php

namespace backend;//Declaring. Code below belongs to backend namespace

class users
{
    private int $user_id;
    private string $first_name;
    private string $last_name;

    public function __construct(int $id, string $first_name, string $last_name)
    {
        $this->user_id = $id;
        $this->first_name = $first_name;
        $this->last_name = $last_name;
    }

    public function userName(): string
    {
        return "$this->first_name $this->last_name";
    }

    public function userId(): string
    {
        return "$this->user_id";
    }
}

classes/frontend/html.php:

<?php

namespace frontend;

class html
{
    public function pageTitle(string $title): void
    {
        echo "<title>$title</title>";
    }

    public function tagOpen(string $tag): void
    {
        echo "<$tag>";
    }

    public function tagClose(string $tag): void
    {
        echo "</$tag>";
    }
}

classes/frontend/style.php:

<?php

namespace frontend;

class style
{
    public function __construct()
    {
        echo "<style>body{background-color:#b5cde5;};</style>";
    }
}

Source code from index.php output:

<head><title>Gary Bilbo</title><style>body{background-color:#b5cde5;};</style></head>1