PHP

Lesson 08

Autoloading and namespaces

Use namespaces and autoloaded classes so file structure, ownership, and dependencies are explicit.

Good Code

src/Service/UserProfileService.php
<?php declare(strict_types=1);

namespace App\Service;

use App\Repository\UserRepository;

final class UserProfileService
{
    public function __construct(private UserRepository $users) {}

    public function profileFor(int $userId): array
    {
        return $this->users->findProfile($userId);
    }
}

Bad Code

profile.php
<?php

require_once 'db.php';
require_once 'users.php';
require_once 'helpers.php';

function profile_for($id) {
    global $db;
    return find_profile($db, $id);
}

Review Notes

What to review

Good Code

The good version gives the class a namespace, injects its dependency, and lets autoloading connect files to class names.

Bad Code

The bad version depends on include order, global state, and free functions whose ownership is hard to trace.

Takeaways

  • Modern PHP code should make class ownership visible through namespaces instead of require chains.