Skip to main content

Autoloading

Chapter Overview

In this chapter you will learn:

  • What autoloading is
  • Why autoloading exists
  • Problems before autoloading
  • require and include problems
  • spl_autoload_register()
  • Composer autoloading
  • PSR-4 standard
  • Namespace resolution
  • Framework architecture
  • PocketMine loading system
  • Enterprise examples
  • Best practices

Introduction

Autoloading is one of the most important concepts in modern PHP.

Without autoloading:

Laravel would not exist.
Composer would not work.
PocketMine would become impossible to maintain.

Almost every modern PHP project relies heavily on autoloading.


The Problem Before Autoloading

Imagine your project:

User.php
Database.php
Config.php
AuthService.php
RankManager.php
PacketManager.php

Before using a class, you had to manually include it.

Example:

require_once "User.php";
require_once "Database.php";
require_once "Config.php";
require_once "AuthService.php";
require_once "PacketManager.php";

This becomes horrible in large applications.


Large Project Example

1000+ Classes

Imagine:

require_once "Class1.php";
require_once "Class2.php";
require_once "Class3.php";

Impossible to manage.


Main Problems

❌ Huge files

❌ Slow loading

❌ Hard maintenance

❌ Circular includes

❌ Human mistakes


Solution

Autoloading

What is Autoloading?

Autoloading means:

Automatically loading classes
when they are needed.

Instead of:

require_once

PHP loads files automatically.


Visualization

new User()

PHP checks:
Is class loaded?

NO

Autoloader executes

User.php loaded

Class created

Simple Example

$user =
new User();

PHP automatically loads:

User.php

without manually including it.


How Does It Work?

PHP provides:

spl_autoload_register()

What is SPL?

SPL means:

Standard PHP Library

Basic Syntax

spl_autoload_register(
function($class)
{

}
);

First Autoloader

spl_autoload_register(
function($class)
{
require $class . ".php";
}
);

Usage:

$user =
new User();

PHP automatically loads:

User.php

Visualization

Class Requested

Autoloader

File Found

File Included

More Realistic Example

Project:

classes/
├── User.php
├── Database.php
└── Config.php

Autoloader:

spl_autoload_register(
function($class)
{
require
"classes/"
. $class
. ".php";
}
);

Problem

Namespaces now exist.

Example:

new App\Models\User();

PHP receives:

App\Models\User

which is not a file.


Solution

Replace:

\

with:

/

Example:

spl_autoload_register(
function($class)
{
$class =
str_replace(
"\\",
"/",
$class
);

require
$class
. ".php";
}
);

Visualization

App\Models\User

App/Models/User

App/Models/User.php

PSR-4

Modern PHP uses:

PSR-4 Autoloading

What is PSR-4?

PSR means:

PHP Standards Recommendation

PSR-4 defines:

How namespaces map to folders.

Example

Namespace:

namespace App\Models;

Class:

class User {

}

File:

src/Models/User.php

Visualization

Namespace

Folder

File

Why PSR-4 Exists

Before PSR-4:

Every framework created its own loading system.

Chaos.

PSR-4 standardized everything.


Composer

Composer is PHP's package manager.

Composer heavily relies on:

Autoloading

Example composer.json

{
"autoload": {

"psr-4": {

"App\\": "src/"

}

}
}

Meaning:

Namespace:

App\

Folder:

src/

Example

Class:

namespace App\Services;

class AuthService {

}

Composer automatically loads:

src/Services/AuthService.php

Running Composer

After editing:

composer.json

Run:

composer dump-autoload

This generates:

vendor/autoload.php

Loading Composer

Example:

require
"vendor/autoload.php";

Done.

Everything loads automatically.


Composer Visualization

Application

vendor/autoload.php

Composer Autoloader

PSR-4 Mapping

File Loaded

Internal Process

new User()

Composer checks map

Find namespace

Convert namespace to path

Load file

Example

new App\Models\User();

Composer:

App\

src/

Models/User.php

Folder Structure Example

project/

├── composer.json
├── vendor/
├── src/
│ ├── Models/
│ ├── Services/
│ └── Controllers/

Enterprise Example

Large projects:

src/

├── Controllers
├── Models
├── Services
├── DTO
├── Events
├── Repositories
├── Exceptions
└── Contracts

Composer loads all of them.


PocketMine Example

PocketMine plugins also use autoloading.


Structure

src/
└── zyro/
├── Main.php
├── commands/
├── listeners/
├── forms/
└── managers/

Namespaces:

namespace zyro;

namespace zyro\commands;

namespace zyro\forms;

PocketMine automatically loads these classes.


Example

use zyro\commands\TestCommand;

No:

require_once

needed.


Why?

PocketMine registers its own autoloader.


PocketMine Internal Flow

Plugin Loaded

plugin.yml

Main Class

Autoloader

All Classes Available

ZyroNetwork Example


Structure

src/

├── api/
├── database/
├── ranks/
├── network/
├── forms/
├── commands/
└── utils/

Namespaces:

zyro\api
zyro\ranks
zyro\network
zyro\database

Autoloading automatically handles everything.


Manual Loading vs Autoloading


Old Method

require_once

Problems:

❌ Ugly

❌ Slow

❌ Hard maintenance


Autoloading

Benefits:

✅ Automatic

✅ Clean

✅ Faster development

✅ Scalable


Multiple Autoloaders

PHP allows multiple autoloaders.

Example:

spl_autoload_register(
function() {

}
);

spl_autoload_register(
function() {

}
);

PHP tries them one by one.


Visualization

Class Requested

Autoloader #1

Not Found

Autoloader #2

Found

Classmap Autoloading

Composer also supports:

{
"autoload": {

"classmap": [

"src/"
]

}
}

Composer scans files.

Creates map:

User

src/User.php

Files Autoloading

{
"autoload": {

"files": [

"helpers.php"
]

}
}

Useful for:

Functions
Constants
Helpers

Performance

Composer creates optimized maps.

Run:

composer dump-autoload -o

This creates:

Optimized Class Maps

Useful for production servers.


Common Beginner Mistakes


Wrong Namespace

Example:

namespace App\Service;

Folder:

src/Services/

Mismatch.

Autoload fails.


Wrong File Name

User.php

Class:

class Users {

}

Confusing.


Wrong Capitalization

Windows:

Works

Linux:

Breaks

Always keep:

Namespace
=
Folder
=
File

Best Practices

✅ Follow PSR-4

✅ Use Composer

✅ Avoid manual require_once

✅ Use optimized autoload

✅ Keep namespaces clean


Real Enterprise Flow

Request

Controller

Service

Repository

Database

Every class is autoloaded automatically.


Framework Flow

Application

Composer

Autoload

Namespaces

Class Files

Exercises


Exercise 1

Create your own autoloader using:

spl_autoload_register()

Exercise 2

Create structure:

src/
├── Models
├── Services
└── Controllers

and autoload them.


Exercise 3

Create:

composer.json

with PSR-4 mapping.


Mini Project

Create:

ZyroNetwork Framework

Structure:

src/

├── API
├── Commands
├── Events
├── Database
├── Network
├── Forms
├── Utils
└── Managers

Configure Composer autoloading.


Interview Questions


What is autoloading?

Automatically loading classes when needed.


Why is autoloading important?

Because large projects cannot manually include thousands of files.


What function registers autoloaders?

spl_autoload_register()

What is PSR-4?

A standard that maps namespaces to folders.


Why does Composer need autoloading?

To automatically load packages and classes.


What command regenerates Composer autoload files?

composer dump-autoload

What file should usually be included?

require "vendor/autoload.php";

Summary

Autoloading provides:

✅ Automatic Class Loading

✅ Cleaner Code

✅ Better Architecture

✅ Composer Support

✅ Framework Development

✅ Enterprise Scalability

Modern PHP applications completely depend on autoloading.

Without autoloading, frameworks like Laravel, Symfony and PocketMine would become extremely difficult to maintain.


References

https://www.php.net/manual/en/function.spl-autoload-register.php

https://www.php-fig.org/psr/psr-4/

https://getcomposer.org/doc/01-basic-usage.md


Next Chapter

➡ Dependency Injection

➡ SOLID Principles

➡ Design Patterns

➡ Service Containers