Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Namespaces and Composer

A real project consists of dozens or hundreds of files. To keep them manageable, classes are placed in folders, given compound names and loaded automatically. Namespaces and Composer take care of this.

The examples in this lesson consist of several files, so they cannot be run here.

Namespaces

Each class lives in its own file. The namespace keyword at the top of the file sets a "folder" for the class name:

<?php
// src/Models/User.php
 
namespace App\Models;
 
class User
{
    public function __construct(public string $name) {}
}

The full name of this class is App\Models\User. That is why a project can have two User classes — yours and one from someone else's library, say — without a conflict.

Using a class

To avoid writing the full name every time, import the class with use:

<?php
// public/index.php
 
use App\Models\User;
 
require __DIR__ . '/../vendor/autoload.php';
 
$user = new User('Anna');
 
echo $user->name;

The require line loads the autoloader — more on that below.

Composer

Composer is PHP's dependency manager. It installs libraries and generates an autoloader that includes the file with a class the first time the class is used. Project settings live in composer.json:

{
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}

This entry means: look for classes whose name starts with App\ in the src/ folder. The class App\Models\User must be in the file src/Models/User.php. This mapping of names to paths is called the PSR-4 standard.

After changing the settings, regenerate the autoloader:

composer dump-autoload

Installing libraries

A library is installed with one command:

composer require monolog/monolog

Composer downloads it into the vendor/ folder, adds it to composer.json and records the exact versions in composer.lock. The library's classes are available through the same autoloader — you never include its files by hand.

What to keep in the repository

FileKeepWhy
composer.jsonYesThe list of dependencies
composer.lockYesExact versions for every developer
vendor/NoRestored with composer install

A common mistake

The class name, the file name and the path must match exactly, including letter case. On Windows a file named user.php works for a class User; on a Linux server it does not: user.php and User.php are different files there. A "class not found" error after deploying almost always means a case mismatch.

Thanks for reading!

Donate to the site — we work hard for you.