Skip to content
LumenaryAcademy
Professional 70 min

The ecosystem, and a complete project

How PHP teams work every day — Composer, autoloading and the PSR standards, PHPUnit, static analysis and formatting, Laravel and Symfony — and a small, complete application built the same way.

Code tested · 2AI-draftedAwaiting review by a computer scientist
MotivationH

From scripts to software

Everything so far has fitted in one file. Real applications have hundreds of classes, depend on dozens of libraries written by other people, are changed by several developers at once, and must keep working after every change. The PHP community built a shared toolkit for that in the early 2010s, and it is the reason modern PHP feels so different from the PHP of tutorials past:

  • Composer installs libraries and generates an autoloader, so new SomeClass() finds the right file by itself.
  • The PHP-FIG (Framework Interoperability Group) publishes PSRs, standards that let libraries and frameworks fit together: a common autoloading layout, a common logger interface, common HTTP objects.
  • PHPUnit tests the code; static analysers check it without running it; formatters keep its style uniform.
  • Frameworks such as Laravel and Symfony provide routing, templates, databases, queues and security, built from those same pieces.

This lesson walks through each, then puts the whole course together in a small application written the way a professional team would write it.

DefinitionsH

Composer, namespaces and autoloading

Install Composer from getcomposer.org. A project is described by a composer.json at its root:

json
{
    "name": "example/library-loans",
    "description": "Lending books at a small community library",
    "type": "project",
    "license": "MIT",
    "require": {
        "php": ">=8.4",
        "ext-pdo_sqlite": "*",
        "psr/log": "^3.0"
    },
    "require-dev": {
        "phpunit/phpunit": "^12.0",
        "phpstan/phpstan": "^2.0"
    },
    "autoload": {
        "psr-4": { "Library\\": "src/" }
    },
    "autoload-dev": {
        "psr-4": { "Library\\Tests\\": "tests/" }
    },
    "scripts": {
        "test": "phpunit",
        "analyse": "phpstan analyse src tests --level 8"
    }
}

The everyday commands:

bash
composer require psr/log           # add a dependency (and update composer.json)
composer require --dev phpunit/phpunit
composer install                   # install exactly the versions in composer.lock
composer update psr/log            # move a dependency to the newest allowed version
composer audit                     # report installed packages with known security advisories
composer test                      # run a script defined in composer.json

Definition— Version constraint

^3.0 means "3.0 or later, but below 4.0": any release that, under semantic versioning, should not break your code. ~3.1 means "3.1 or later, below 4.0" as well, and ~3.1.2 means "below 3.2". require lists what the application needs to run; require-dev lists tools only developers and CI need.

Definition— composer.lock

The exact version of every package installed, including dependencies of dependencies, written by composer update and read by composer install. Applications commit it, so every developer, the CI server and production run identical code. (Libraries usually do not, because their users' projects choose the versions.)

Definition— Namespace

A prefix that groups names, like a folder for classes: namespace Library\Domain; at the top of a file puts its classes in Library\Domain, and use Library\Domain\Loan; lets another file refer to it as plain Loan. Namespaces stop two libraries' Client classes from colliding.

Definition— PSR-4 autoloading

A convention that maps a namespace prefix to a directory: with "Library\\": "src/", the class Library\Domain\Loan lives in src/Domain/Loan.php. One class per file, the file named after the class.

Composer writes vendor/autoload.php, which your entry script requires once. From then on, the first time code mentions a class PHP has not seen, PHP calls the registered autoloader, which turns the class name into a file path and loads it. The program below builds a one-class project on disk and registers a small PSR-4 autoloader by hand, so you can watch it work:

php
<?php

declare(strict_types=1);

// Set up a tiny project on disk: src/Greeting/Formal.php declares App\Greeting\Formal.
$root = sys_get_temp_dir() . "/autoload-demo-" . getmypid();
mkdir("$root/src/Greeting", recursive: true);
file_put_contents("$root/src/Greeting/Formal.php", <<<'PHP'
    <?php
    declare(strict_types=1);
    namespace App\Greeting;

    final class Formal
    {
        public function greet(string $name): string
        {
            return "Good evening, $name.";
        }
    }
    PHP);

// A PSR-4 autoloader: namespace prefix App\ maps to the directory src/.
spl_autoload_register(function (string $class) use ($root): void {
    $prefix = "App\\";
    if (!str_starts_with($class, $prefix)) {
        return;                                   // not ours: let other autoloaders try
    }
    $relative = str_replace("\\", "/", substr($class, strlen($prefix)));
    $file = "$root/src/$relative.php";
    echo "(autoloading $class from src/$relative.php)\n";
    if (is_file($file)) {
        require $file;
    }
});

echo "Before first use: ", class_exists("App\\Greeting\\Formal", autoload: false) ? "loaded" : "not loaded", "\n";
$greeter = new App\Greeting\Formal();             // triggers the autoloader
echo $greeter->greet("Dr. Okonkwo"), "\n";
echo (new App\Greeting\Formal())->greet("Ms. Lindqvist"), "\n";   // already loaded: no second message

unlink("$root/src/Greeting/Formal.php");
rmdir("$root/src/Greeting");
rmdir("$root/src");
rmdir($root);
text
Before first use: not loaded
(autoloading App\Greeting\Formal from src/Greeting/Formal.php)
Good evening, Dr. Okonkwo.
Good evening, Ms. Lindqvist.

The class is loaded only when it is first used, and only once. Composer's real autoloader works the same way, with a few optimisations: in production, composer install --no-dev --optimize-autoloader precomputes a map from every class to its file.

ExplanationH

Standards and the tools teams run on every change

PSRs you will meet. The PHP-FIG has accepted standards for many shared needs; these are the ones that show up most:

StandardWhat it defines
PSR-1, PSR-12, PER Coding StyleHow PHP code is formatted: braces, spacing, naming, imports. PER Coding Style is the maintained successor of PSR-12.
PSR-4Autoloading: namespace prefix to directory.
PSR-3LoggerInterface, with info(), error() and the other levels. Monolog is the common implementation.
PSR-7, PSR-17Immutable HTTP request and response objects, and factories to create them.
PSR-15HTTP handlers and middleware built on PSR-7.
PSR-11ContainerInterface for dependency-injection containers.
PSR-18An HTTP client interface, so a library can make requests without choosing Guzzle or Symfony's client for you.
PSR-20ClockInterface, a standard version of the Clock you wrote in the classes lesson.

Testing with PHPUnit. Tests live in tests/, one test class per class under test. Here is how the project at the end of this lesson would be tested with PHPUnit (this file needs PHPUnit installed through Composer, so it is not run by this course's own test suite):

php
<?php
declare(strict_types=1);

namespace Library\Tests;

use DateTimeImmutable;
use Library\Application\LoanService;
use Library\Domain\LoanRefused;
use Library\Infrastructure\{ManualClock, PdoLoanRepository};
use PDO;
use PHPUnit\Framework\Attributes\{DataProvider, Test};
use PHPUnit\Framework\TestCase;

final class LoanServiceTest extends TestCase
{
    private ManualClock $clock;
    private LoanService $service;

    protected function setUp(): void
    {
        $this->clock = new ManualClock(new DateTimeImmutable("2026-11-02"));
        $this->service = new LoanService(new PdoLoanRepository(new PDO("sqlite::memory:")), $this->clock);
    }

    #[Test]
    public function aBookCannotBeLentTwice(): void
    {
        $this->service->borrow("BK-101", "Amaka");
        $this->expectException(LoanRefused::class);
        $this->service->borrow("BK-101", "Jonas");
    }

    /** @return iterable<string, array{int, int}> days kept => expected fine in cents */
    public static function lateness(): iterable
    {
        yield "on the due date" => [21, 0];
        yield "one day late" => [22, 20];
        yield "a week late" => [28, 140];
    }

    #[Test]
    #[DataProvider("lateness")]
    public function finesGrowWithEachLateDay(int $daysKept, int $expectedCents): void
    {
        $loan = $this->service->borrow("BK-101", "Amaka");
        $this->clock->advance($daysKept);
        self::assertSame($expectedCents, $this->service->giveBack($loan->id));
    }
}

setUp() runs before every test, so each starts with a fresh in-memory database and a clock at a known date: no test depends on another, or on today's date. Attributes mark tests (#[Test], or a method name starting with test) and connect a data provider that runs one test with several inputs, each reported by name. assertSame compares with ===, which is what you almost always want (assertEquals compares loosely). Run the suite with vendor/bin/phpunit. Pest, built on PHPUnit, offers a terser function-based syntax that many Laravel teams prefer.

The other tools in a typical pipeline:

  • PHPStan or Psalm for static analysis, at the strictest level the codebase can bear.
  • PHP-CS-Fixer or PHP_CodeSniffer to check and fix formatting against PER Coding Style, so code review never discusses spaces.
  • Rector for automated refactoring and PHP-version upgrades.
  • Xdebug for step debugging in your editor and for test-coverage reports (PCOV is a faster coverage-only alternative).

A continuous-integration job (GitHub Actions, GitLab CI or similar) runs composer install, the formatter in check mode, the analyser and the tests on every pull request, usually on each PHP version the project supports. Nothing is merged until all of them pass.

Further reading

Frameworks and how PHP applications run

Few teams build web applications from bare PHP. Two frameworks dominate:

  • Laravel, first released in 2011 by Taylor Otwell, is a "batteries included" framework focused on developer happiness: expressive routing, the Eloquent ORM (each table is a class, each row an object), Blade templates, the Artisan command line, queues, scheduled jobs, mail, authentication scaffolding and a large ecosystem of official packages and hosted services. It favours convention and short code.
  • Symfony, first released in 2005 by Fabien Potencier, is a set of decoupled, reusable components (HTTP foundation, routing, console, dependency injection, forms, validation, security, serializer) and a full-stack framework that assembles them, usually with Doctrine ORM and Twig templates. It favours explicit configuration and long-term stability. Its components are used far beyond Symfony itself, including inside Laravel and Drupal.

Both give you the patterns from this course out of the box: a front controller that routes each request, a container that injects dependencies, a request-level exception handler, automatic output escaping in templates, CSRF tokens in forms, prepared statements through the ORM, and testing helpers. Smaller options include Slim (a micro-framework built on PSR-7 and PSR-15) and Laminas (the continuation of Zend Framework). And a great deal of PHP work happens inside content management systems: WordPress (themes and plugins) and Drupal.

Running in production. The classic setup is nginx (or Apache) in front of PHP-FPM, with OPcache enabled so compiled code stays in memory; containers package the same arrangement. Application servers such as FrankenPHP, RoadRunner and Swoole can keep the framework booted between requests ("worker mode") for lower latency; Laravel supports them through Octane. In worker mode the shared-nothing rule from the first lesson no longer holds automatically, so static properties and long-lived objects must not carry one request's data into the next.

Worked examplesH

A complete project: a community library's loans

Here is a small but complete application in the style of this course. A community library lends books for three weeks, allows each member at most two books at a time, and charges a small fine for each day late. The program contains the domain (a readonly Loan and an exception type), interfaces for the clock and the storage, a PDO implementation of the storage, an application service with the rules, a tiny test runner standing in for PHPUnit, and a short simulation.

php
<?php

declare(strict_types=1);

// In a real project each class lives in its own file under src/, found by Composer's
// PSR-4 autoloader. Here the namespaces are written with braces so it all fits in one file.

namespace Library\Domain {

    use DateTimeImmutable;

    final readonly class Loan
    {
        public function __construct(
            public int $id,
            public string $book,
            public string $member,
            public DateTimeImmutable $dueOn,
            public ?DateTimeImmutable $returnedOn = null,
        ) {
        }

        public function isActive(): bool
        {
            return $this->returnedOn === null;
        }

        public function daysLate(DateTimeImmutable $today): int
        {
            $end = $this->returnedOn ?? $today;
            return max(0, (int) $this->dueOn->diff($end)->format("%r%a"));
        }
    }

    final class LoanRefused extends \DomainException
    {
    }

    interface Clock
    {
        public function today(): DateTimeImmutable;
    }

    interface LoanRepository
    {
        public function add(string $book, string $member, DateTimeImmutable $dueOn): Loan;

        public function markReturned(int $loanId, DateTimeImmutable $on): void;

        public function find(int $loanId): ?Loan;

        /** @return list<Loan> */
        public function all(): array;
    }
}

namespace Library\Infrastructure {

    use DateTimeImmutable;
    use Library\Domain\{Clock, Loan, LoanRepository};
    use PDO;

    final class PdoLoanRepository implements LoanRepository
    {
        public function __construct(private readonly PDO $db)
        {
            $this->db->exec("CREATE TABLE IF NOT EXISTS loans (
                id INTEGER PRIMARY KEY, book TEXT NOT NULL, member TEXT NOT NULL,
                due_on TEXT NOT NULL, returned_on TEXT)");
        }

        public function add(string $book, string $member, DateTimeImmutable $dueOn): Loan
        {
            $this->db->prepare("INSERT INTO loans (book, member, due_on) VALUES (?, ?, ?)")
                ->execute([$book, $member, $dueOn->format("Y-m-d")]);
            return new Loan((int) $this->db->lastInsertId(), $book, $member, $dueOn);
        }

        public function markReturned(int $loanId, DateTimeImmutable $on): void
        {
            $this->db->prepare("UPDATE loans SET returned_on = ? WHERE id = ?")->execute([$on->format("Y-m-d"), $loanId]);
        }

        public function find(int $loanId): ?Loan
        {
            $query = $this->db->prepare("SELECT * FROM loans WHERE id = ?");
            $query->execute([$loanId]);
            $row = $query->fetch(PDO::FETCH_ASSOC);
            return $row === false ? null : $this->toLoan($row);
        }

        public function all(): array
        {
            $rows = $this->db->query("SELECT * FROM loans ORDER BY id")->fetchAll(PDO::FETCH_ASSOC);
            return array_map($this->toLoan(...), $rows);
        }

        /** @param array<string, mixed> $row */
        private function toLoan(array $row): Loan
        {
            return new Loan(
                (int) $row["id"],
                $row["book"],
                $row["member"],
                new DateTimeImmutable($row["due_on"]),
                $row["returned_on"] === null ? null : new DateTimeImmutable($row["returned_on"]),
            );
        }
    }

    /** A clock you can move by hand: used in tests and in this demonstration. */
    final class ManualClock implements Clock
    {
        public function __construct(private DateTimeImmutable $now)
        {
        }

        public function today(): DateTimeImmutable
        {
            return $this->now;
        }

        public function advance(int $days): void
        {
            $this->now = $this->now->modify("+$days days");
        }
    }
}

namespace Library\Application {

    use Library\Domain\{Clock, Loan, LoanRefused, LoanRepository};

    final class LoanService
    {
        public const int LOAN_DAYS = 21;
        public const int MAX_ACTIVE_LOANS = 2;
        public const int FINE_CENTS_PER_DAY = 20;

        public function __construct(
            private readonly LoanRepository $loans,
            private readonly Clock $clock,
        ) {
        }

        public function borrow(string $book, string $member): Loan
        {
            $active = array_filter($this->loans->all(), fn(Loan $l): bool => $l->isActive());
            if (array_any($active, fn(Loan $l): bool => $l->book === $book)) {
                throw new LoanRefused("$book is already on loan");
            }
            if (count(array_filter($active, fn(Loan $l): bool => $l->member === $member)) >= self::MAX_ACTIVE_LOANS) {
                throw new LoanRefused("$member already has " . self::MAX_ACTIVE_LOANS . " books");
            }
            $due = $this->clock->today()->modify("+" . self::LOAN_DAYS . " days");
            return $this->loans->add($book, $member, $due);
        }

        /** Returns the fine owed, in cents. */
        public function giveBack(int $loanId): int
        {
            $loan = $this->loans->find($loanId) ?? throw new LoanRefused("no loan $loanId");
            if (!$loan->isActive()) {
                throw new LoanRefused("loan $loanId was already returned");
            }
            $this->loans->markReturned($loanId, $this->clock->today());
            return $loan->daysLate($this->clock->today()) * self::FINE_CENTS_PER_DAY;
        }

        /** @return list<string> one line per loan */
        public function report(): array
        {
            $today = $this->clock->today();
            return array_map(fn(Loan $l): string => sprintf(
                "#%d %-8s %s  due %s  %s",
                $l->id,
                $l->member,
                $l->book,
                $l->dueOn->format("Y-m-d"),
                $l->isActive() ? ($l->daysLate($today) > 0 ? "OVERDUE by {$l->daysLate($today)} days" : "on loan") : "returned",
            ), $this->loans->all());
        }
    }
}

namespace {

    use Library\Application\LoanService;
    use Library\Domain\LoanRefused;
    use Library\Infrastructure\{ManualClock, PdoLoanRepository};

    function money(int $cents): string
    {
        return sprintf("%d.%02d", intdiv($cents, 100), $cents % 100);
    }

    /** A very small stand-in for PHPUnit, so this file runs on its own. */
    function check(string $name, callable $test): bool
    {
        try {
            $test();
            echo "  ok    $name\n";
            return true;
        } catch (Throwable $e) {
            echo "  FAIL  $name: ", $e->getMessage(), "\n";
            return false;
        }
    }

    function assertSame(mixed $expected, mixed $actual): void
    {
        if ($expected !== $actual) {
            throw new RuntimeException("expected " . var_export($expected, true) . ", got " . var_export($actual, true));
        }
    }

    function makeService(string $startDate = "2026-11-02"): array
    {
        $clock = new ManualClock(new DateTimeImmutable($startDate));
        return [new LoanService(new PdoLoanRepository(new PDO("sqlite::memory:")), $clock), $clock];
    }

    echo "Tests\n";
    $results = [
        check("a loan is due three weeks later", function (): void {
            [$service] = makeService();
            assertSame("2026-11-23", $service->borrow("BK-101", "Amaka")->dueOn->format("Y-m-d"));
        }),
        check("returning on time costs nothing", function (): void {
            [$service, $clock] = makeService();
            $loan = $service->borrow("BK-101", "Amaka");
            $clock->advance(21);
            assertSame(0, $service->giveBack($loan->id));
        }),
        check("each late day costs the daily fine", function (): void {
            [$service, $clock] = makeService();
            $loan = $service->borrow("BK-101", "Amaka");
            $clock->advance(25);
            assertSame(4 * LoanService::FINE_CENTS_PER_DAY, $service->giveBack($loan->id));
        }),
        check("a book cannot be lent twice", function (): void {
            [$service] = makeService();
            $service->borrow("BK-101", "Amaka");
            try {
                $service->borrow("BK-101", "Jonas");
                throw new RuntimeException("no exception");
            } catch (LoanRefused $e) {
                assertSame("BK-101 is already on loan", $e->getMessage());
            }
        }),
    ];
    echo count(array_filter($results)), " of ", count($results), " tests passed\n\n";

    echo "A month at the library\n";
    [$library, $clock] = makeService();
    $first = $library->borrow("BK-101", "Amaka");
    $library->borrow("BK-102", "Amaka");
    $library->borrow("BK-103", "Jonas");
    try {
        $library->borrow("BK-104", "Amaka");
    } catch (LoanRefused $e) {
        echo "refused: ", $e->getMessage(), "\n";
    }
    $clock->advance(24);
    echo "Amaka returns loan #{$first->id}, fine: ", money($library->giveBack($first->id)), "\n";
    echo implode("\n", $library->report()), "\n";
}
text
Tests
  ok    a loan is due three weeks later
  ok    returning on time costs nothing
  ok    each late day costs the daily fine
  ok    a book cannot be lent twice
4 of 4 tests passed

A month at the library
refused: Amaka already has 2 books
Amaka returns loan #1, fine: 0.60
#1 Amaka    BK-101  due 2026-11-23  returned
#2 Amaka    BK-102  due 2026-11-23  OVERDUE by 3 days
#3 Jonas    BK-103  due 2026-11-23  OVERDUE by 3 days

How the course's ideas show up:

  • Layers in namespaces. Library\Domain holds the concepts and has no idea that SQL exists. Library\Infrastructure holds the PDO repository and the clock. Library\Application holds the rules. In a Composer project these would be the folders src/Domain, src/Infrastructure and src/Application, one class per file; the braces syntax namespace X { … } exists so several namespaces can share a file, which is rare outside examples like this.
  • Readonly value object. A Loan never changes; returning a book updates the database, and the next find() builds a new Loan.
  • Interfaces at the boundaries. LoanService asks for a LoanRepository and a Clock. The tests and the simulation pass an in-memory SQLite database and a ManualClock that can jump forward, so "25 days later" takes no time at all. A web controller would pass a MySQL or PostgreSQL connection and a real clock (in practice, a PSR-20 clock from a package such as symfony/clock).
  • Prepared statements everywhere in the repository, and a private toLoan() that turns rows into objects in one place.
  • Exceptions for broken rules. LoanRefused is thrown for a book already on loan, a member over the limit, or a bad loan id, with a message that a controller could show (or translate) and a type it can catch.
  • Money as integer cents, formatted only for display, and constants such as LOAN_DAYS that name the library's rules.
  • Tests first in the output, each one setting up its own fresh world.

Ideas for extending it, each of which practises a part of the course: add a MemberId value object instead of plain strings; add a LoanStatus enum with Overdue; write the PHPUnit test class above for real in a Composer project and run PHPStan at level 8 on it; or put a small web form in front of borrow() with the validation, escaping and CSRF protection from the previous lesson.

Common misconceptionsH

Common misunderstandings

Misconception

"Deploying means running composer update on the server." update picks new versions, so production would run code nobody has tested. Run composer update on a development machine, test, commit composer.lock, and let every other environment run composer install, which installs exactly what the lock file says.

Misconception

"The vendor/ folder belongs in version control." It is generated from composer.json and composer.lock and can always be rebuilt, so it goes in .gitignore. Committing it bloats the repository and invites people to edit third-party code in place, where the next install silently undoes their change.

Misconception

"Using a framework makes my application secure." A framework makes the safe path the easy one: escaped template output, bound query parameters, CSRF tokens. Each one also has a way out, such as raw output in Blade or Twig, raw SQL strings and routes excluded from CSRF checks, and those exits are where vulnerabilities live. Know where your code leaves the paved road, and review those places with extra care.

Further reading

Where to go next

You now know the language that the PHP manual documents, and how working PHP developers use it. Good next steps:

  • Build something real with a framework. Follow the official getting-started guide of Laravel or Symfony and build a small application end to end, with tests.
  • Read the RFCs for features you use. The discussion on wiki.php.net/rfc explains why each feature looks the way it does, and the release pages on php.net list what each version changed.
  • Read PHP The Right Way for a community overview of current practice, and the OWASP cheat sheets whenever you handle input, sessions or files.
  • Contribute. Many PHP libraries on GitHub welcome help with documentation, tests and small fixes, and reading a well-maintained library's code is one of the fastest ways to absorb a professional style.
Exercises

Exercises

1. The ecosystem, and a complete project

Warm-upHuman

Your application's composer.lock is committed. Which command should the deployment script run on the production server?

Choose one

2. The ecosystem, and a complete project

CoreHuman

A composer.json has "autoload": { "psr-4": { "Shop\\": "src/" } }. In which file must the class Shop\Billing\Invoice\Pdf be defined? Give the path relative to the project root.

3. The ecosystem, and a complete project

CoreHuman

A project requires "vendor/package": "^2.3". Which of these versions may Composer install? List the letters.

  • a: 2.2.9
  • b: 2.3.0
  • c: 2.9.1
  • d: 3.0.0
  • e: 2.3.7

Write elements separated by commas. Order and repeats don’t matter — just like in a set!

4. The ecosystem, and a complete project

Warm-upHuman

You are writing a library and want it to log warnings without forcing a particular logging package on your users. Which standard should its constructor accept?

Choose one

5. The ecosystem, and a complete project

CoreComputational

With the project's rules (loans last 21 days, the fine is 20 cents per late day), a member borrows a book on 2 November 2026 and returns it on 2 December 2026. What does giveBack return, in cents?

6. The ecosystem, and a complete project

StretchComputational

Someone changes LOAN_DAYS in the project from 21 to 14 and runs the program. Which of its four tests fail? Answer with their numbers.

  1. a loan is due three weeks later
  2. returning on time costs nothing (advances 21 days)
  3. each late day costs the daily fine (advances 25 days, expects 4 days' fine)
  4. a book cannot be lent twice

Write elements separated by commas. Order and repeats don’t matter — just like in a set!

7. The ecosystem, and a complete project

StretchHuman

An application caches the logged-in user in a static property, Auth::$current, set at the start of each request. It works under PHP-FPM. After moving to FrankenPHP's worker mode, users occasionally see someone else's name. Why?

Choose one

Further reading and resources