Explain it simply
Explain it simply
You have now met every basic piece of PHP: variables, arrays, functions, forms, sessions, classes, exceptions and databases. Knowing the pieces is like owning a full set of kitchen tools: you only learn how they work together by cooking a meal.
So the best next step is not one more tutorial but a small project in which data comes in from an input, passes through checks, lands in storage and comes back out as a report.
Problem → Why → Solution
The problem: freezing in front of an empty file
A common trap after finishing a course is tutorial hopping. You can follow every example, yet you freeze in front of an empty file. The knowledge sits in separate boxes: one lesson for arrays, one for forms, one for PDO. A real feature needs all of them in one place and in the right order.
Without practice at joining them, code turns into one long script where validation, SQL and printing are mixed together, like the loop below. The cure is a small project where you have to decide for yourself where each responsibility lives.
<?php
// Parsing, checking, SQL and printing all tangled in one loop.
foreach ($rows as $row) {
if ($row['amount'] > 0) {
$pdo->query("INSERT INTO expenses VALUES
(NULL, '{$row['title']}', {$row['amount']})");
echo 'Saved ' . $row['title'] . '<br>';
}
}Why aren't separate lessons enough?
Each lesson shows one tool in isolation. What it cannot show are the seams between the tools: where input becomes a typed object, where an error is caught, where SQL is hidden. Choosing those seams is the main job of a project.
Core concept: one job per layer
Picture a small PHP program as a pipeline. Raw data enters at one end, every layer does exactly one job, and a report leaves at the other end. The capstone in this lesson has five layers.
1. Turn raw input into a typed object
An array from a CSV row or a form cannot be trusted. Expense::fromRow() checks it and builds an Expense when it is valid, or throws. Every object that passes this layer already satisfies the rules.
2. Model the domain with types and enums
declare(strict_types=1), an int amountCents, readonly properties and an enum Category make invalid values impossible to construct. An unknown category such as "gifts" yields null from Category::tryFrom() and is rejected.
3. Let exceptions carry rule violations
ValidationException is caught around each row of the loop. One bad row does not stop the import: the good rows go on, and the bad ones are listed with their reasons.
4. A repository hides the SQL
ExpenseRepository wraps the PDO prepared statements, so the rest of the code uses add() and all() without knowing any SQL. The CHECK (amount_cents > 0) in the table is the second line of defence.
5. Array functions build the report
array_map, array_sum, max, array_search and arsort turn the list of objects into totals and a ranking. Keeping the calculations as plain functions over arrays makes them easy to test.
| Course topic | Where it appears in the capstone |
|---|---|
| Type declarations and strict types | declare(strict_types=1), int $amountCents, readonly |
| Classes and objects | Expense and ExpenseRepository |
| Exceptions | ValidationException caught per row |
| Arrays | array_map, array_sum, arsort, max |
| PDO and prepared statements | add() and all() in the repository |
| Validation and constraints | filter_var, Category::tryFrom, CHECK |
What separates a tutorial example from a project is decisions: where validation lives, which errors you catch, which type holds money. Only after you have made those decisions yourself do you start to understand the shape of code.
- Raw rows arrive as plain arrays
- fromRow() makes a valid Expense or throws
- The repository stores and reloads them
- Array functions build the report
Each layer does only its own job, so when the report looks wrong you know which layer to open.
General pattern
<?php
foreach ($rawRows as $line => $raw) {
try {
$repository->add(Entity::fromRow($raw));
} catch (ValidationException $problem) {
$rejected[] = "row $line: " . $problem->getMessage();
}
}
$items = $repository->all();
$total = array_sum(array_map(fn (Entity $e) => $e->value, $items));Each row is turned into a valid object and stored inside a try. A ValidationException skips just that row and records the reason. Afterwards the objects are reloaded and calculated with array functions.
Capstone: an expense import and report
This single file contains every major part of the course. Eight prepared raw rows (some of them invalid) are turned into Expense objects, stored in an in-memory SQLite database, and summarised as totals per category plus the biggest expense. Notice that money is kept as integer cents, not as a float. PDO runs against SQLite, so no MySQL server is needed; the course's MySQL lessons write the same kind of SQL.
<?php
declare(strict_types=1);
final class ValidationException extends InvalidArgumentException
{
}
enum Category: string
{
case Food = 'food';
case Transport = 'transport';
case Fun = 'fun';
public static function fromInput(string $text): self
{
return self::tryFrom(strtolower(trim($text)))
?? throw new ValidationException("Unknown category '$text'");
}
}
final class Expense
{
public function __construct(
public readonly string $title,
public readonly int $amountCents,
public readonly Category $category,
) {
if ($title === '') {
throw new ValidationException('Title is required');
}
if ($amountCents <= 0) {
throw new ValidationException('Amount must be positive');
}
}
/** Build an Expense from raw, untrusted input such as a CSV row or a form. */
public static function fromRow(array $row): self
{
$amount = filter_var($row['amount'] ?? '', FILTER_VALIDATE_FLOAT);
if ($amount === false) {
throw new ValidationException('Amount is not a number');
}
return new self(
trim((string) ($row['title'] ?? '')),
(int) round($amount * 100),
Category::fromInput((string) ($row['category'] ?? '')),
);
}
}
final class ExpenseRepository
{
public function __construct(private PDO $pdo)
{
$this->pdo->exec('CREATE TABLE expenses (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
amount_cents INTEGER NOT NULL CHECK (amount_cents > 0),
category TEXT NOT NULL
)');
}
public function add(Expense $expense): void
{
$stmt = $this->pdo->prepare(
'INSERT INTO expenses (title, amount_cents, category)
VALUES (:title, :amount, :category)'
);
$stmt->execute([
'title' => $expense->title,
'amount' => $expense->amountCents,
'category' => $expense->category->value,
]);
}
/** @return Expense[] */
public function all(): array
{
$sql = 'SELECT title, amount_cents, category FROM expenses ORDER BY id';
$toExpense = fn (array $r): Expense => new Expense(
$r['title'],
(int) $r['amount_cents'],
Category::from($r['category'])
);
return array_map($toExpense, $this->pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC));
}
}
function money(int $cents): string
{
return number_format($cents / 100, 2);
}
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$repo = new ExpenseRepository($pdo);
$rawRows = [
['title' => 'Noodles', 'amount' => '3.50', 'category' => 'food'],
['title' => 'Bus pass', 'amount' => '12', 'category' => 'Transport'],
['title' => 'Cinema', 'amount' => '8.25', 'category' => 'fun'],
['title' => 'Rice', 'amount' => '4.75', 'category' => ' FOOD '],
['title' => '', 'amount' => '5', 'category' => 'food'],
['title' => 'Taxi', 'amount' => 'free', 'category' => 'transport'],
['title' => 'Gift', 'amount' => '20', 'category' => 'gifts'],
['title' => 'Refund', 'amount' => '-4', 'category' => 'fun'],
];
$rejected = [];
foreach ($rawRows as $line => $row) {
try {
$repo->add(Expense::fromRow($row));
} catch (ValidationException $e) {
$rejected[] = 'row ' . ($line + 1) . ': ' . $e->getMessage();
}
}
$expenses = $repo->all();
echo 'Imported ' . count($expenses) . ' of ' . count($rawRows) . " rows\n";
foreach ($rejected as $message) {
echo " rejected $message\n";
}
$totals = [];
foreach ($expenses as $expense) {
$key = $expense->category->value;
$totals[$key] = ($totals[$key] ?? 0) + $expense->amountCents;
}
arsort($totals);
echo "\nTotals by category:\n";
foreach ($totals as $category => $cents) {
$amount = str_pad(money($cents), 8, ' ', STR_PAD_LEFT);
echo ' ' . str_pad($category, 10) . $amount . "\n";
}
$amounts = array_map(fn (Expense $e) => $e->amountCents, $expenses);
$biggest = $expenses[array_search(max($amounts), $amounts, true)];
echo "\nTotal: " . money(array_sum($amounts)) . "\n";
echo "Biggest: {$biggest->title} (" . money($biggest->amountCents) . ")\n";
echo 'Average: ' . money((int) round(array_sum($amounts) / count($amounts))) . "\n";Code breakdown
- A safe way to turn text into an enum
return self::tryFrom(strtolower(trim($text)))trim and strtolower turn " FOOD " into Category::Food. tryFrom() returns null for an unknown value and ?? throw converts that into a ValidationException.
- Rules enforced in the constructor
throw new ValidationException('Amount must be positive');Because the check is in the constructor, no code anywhere can create an Expense with a bad value, whether it comes from a form or is read back from the database.
- Untrusted input at the edge
$amount = filter_var($row['amount'] ?? '', FILTER_VALIDATE_FLOAT);For non-numbers such as "free", filter_var returns false. The ?? '' means a missing amount field raises no warning.
- Money as whole cents
(int) round($amount * 100),Adding decimal floats can make 0.1 + 0.2 differ from 0.3. Whole cents avoid that, and number_format converts back only when printing.
- The repository's public face
public function add(Expense $expense): voidThe caller hands over an Expense and never sees SQL, placeholders or column names. If you later move to MySQL, only the repository changes.
- One bad row does not stop the import
} catch (ValidationException $e) {The try/catch sits inside the loop. Outside it, the first bad row would stop the whole import. That is why rows 5 to 8 are rejected while the first four are already stored.
- Array functions build the report
$amounts = array_map(fn (Expense $e) => $e->amountCents, $expenses);This pulls just the cents out of the list of objects, and array_sum, max and array_search then give the total, the biggest and the average. Familiar array functions replace long loops.
Imported 4 of 8 rows
rejected row 5: Title is required
rejected row 6: Amount is not a number
rejected row 7: Unknown category 'gifts'
rejected row 8: Amount must be positive
Totals by category:
transport 12.00
food 8.25
fun 8.25
Total: 28.50
Biggest: Bus pass (12.00)
Average: 7.13Where each course topic goes next
Every topic has a first thing worth learning next and a project idea to try it on. Do not attempt them all at once; pick one and finish it.
| Topic | Learn next | Project idea |
|---|---|---|
| Forms and validation | Request objects and rule sets | A registration form with password rules |
| Sessions and security | password_hash, password_verify, session cookie options | A login and logout system |
| Classes and namespaces | Composer autoloading (PSR-4), interfaces, dependency injection | Split the capstone into src/ files |
| PDO and SQL | Migrations, joins, indexes, query logging | Add a categories table and users |
| Exceptions | One central error handler and logging | Log rejected rows to a file |
| Testing | PHPUnit | Write tests for Expense and the repository |
Making the capstone testable with Composer and PHPUnit
Composer is PHP's package manager. The psr-4 autoload rule in composer.json maps the App\ namespace to the src/ folder, so you no longer require every class file by hand. PHPUnit is installed through Composer too. The commands below need Composer on your own machine, so they are not run inside this lesson.
{
"require": {
"php": ">=8.1"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}composer install
composer require --dev phpunit/phpunit
vendor/bin/phpunit testsA test confirms each rule from the capstone. This test class checks two of them: the Expense constructor rule and the normalising of category text. It only works once the code is split into src/ files with Composer, so it is not run here.
<?php
declare(strict_types=1);
namespace Tests;
use App\Category;
use App\Expense;
use App\ValidationException;
use PHPUnit\Framework\TestCase;
final class ExpenseTest extends TestCase
{
public function testRejectsNonPositiveAmounts(): void
{
$this->expectException(ValidationException::class);
new Expense('Refund', -400, Category::Fun);
}
public function testNormalisesCategoryText(): void
{
$this->assertSame(Category::Food, Category::fromInput(' FOOD '));
}
}Frameworks and new PHP releases
Laravel and Symfony are full-stack PHP frameworks that are widely used. They bring routing, a database layer, validation, templates and command-line tools. Pick one and learn it; do not learn both at once. The ideas from this course (request, validate, repository, response) map one-to-one onto any framework, only the names differ.
When a new PHP release comes out, read the official migration guide before upgrading, then run your automated tests to confirm that nothing broke. This lesson does not say which release is the latest one; check php.net for that.
In real projects
In real projects
In a professional PHP project the classes live in a src/ folder. The only file the web server exposes is public/index.php, so the rest is not reachable directly from a browser. Secrets such as passwords stay out of the code and live in environment configuration. Composer manages the dependencies, and a CI system runs the tests plus static analysis tools such as PHPStan or Psalm on every commit.
On a production server display_errors is switched off and errors go to a log, so visitors never see details. HTTPS is used everywhere and the database is backed up regularly. Code review is part of the routine too, because another person reading your code is one of the best ways to catch bugs early.
Common mistakes
Common mistakes
Starting a new course before finishing a project
New knowledge always feels more exciting than a finished project, but you only meet the hard integration problems by taking one project all the way to the end. Rewrite this capstone in your own idea and add one more feature.
Jumping into a framework before the plain flow makes sense
A framework hides how a request is received and how validation and the database are called. Without the plain PHP flow it feels like magic, and when an error appears you cannot tell why.
Testing only the happy path
This capstone is meaningful because it includes four rejected rows (a blank title, a non-numeric amount, an unknown category, a negative amount). If one valid input satisfies you, the program will fail on a real user's bad input.
Storing money as a float
In PHP, 0.1 + 0.2 === 0.3 is false, because most decimal fractions cannot be represented exactly as binary floats. Store money as whole cents, or use the database's DECIMAL type.
Mini challenge
Report the top spending categories
Write two functions that work on plain arrays. topCategories() adds the expenses up per category, sorts the biggest total first and returns only $limit entries. shareOfTotal() turns those totals into whole-number percentages.
- Throw InvalidArgumentException when $limit is negative
- Break ties alphabetically by category name (ksort, then arsort)
- Keep the keys (category names); use array_slice with preserve_keys
- shareOfTotal() returns an empty array for an empty array or a zero total instead of dividing by zero
<?php
declare(strict_types=1);
// An expense is a plain array with the keys title (string),
// category (string) and cents (int).
function topCategories(array $expenses, int $limit): array
{
// TODO: throw InvalidArgumentException when $limit is negative
// TODO: add up the cents per category
// TODO: biggest total first; equal totals stay in A-Z order
// TODO: keep only the first $limit entries, with their keys
}
function shareOfTotal(array $totals): array
{
// TODO: whole-number percent of the grand total, same keys
// TODO: guard against a grand total of 0
}Expected: Two lines appear: transport 1200 cents 59% and food 825 cents 41% (the percentages are computed between those two only). Then limit 0, no data and an empty share each print [], and the last line shows the error "Limit must not be negative".
Show hint
Call ksort($totals) first and arsort($totals) second. PHP 8's sort functions are stable, so categories with equal totals keep their A-Z order. array_map with a single array keeps its keys.
Show solution
<?php
declare(strict_types=1);
/** @return array<string, int> category => total cents, biggest first, at most $limit */
function topCategories(array $expenses, int $limit): array
{
if ($limit < 0) {
throw new InvalidArgumentException('Limit must not be negative');
}
$totals = [];
foreach ($expenses as $expense) {
$category = $expense['category'];
$totals[$category] = ($totals[$category] ?? 0) + $expense['cents'];
}
ksort($totals); // alphabetical first ...
arsort($totals); // ... then biggest first; PHP 8 sorting is stable, so ties stay A-Z
return array_slice($totals, 0, $limit, true);
}
/** @return array<string, int> category => whole-number percent of the grand total */
function shareOfTotal(array $totals): array
{
$grand = array_sum($totals);
if ($grand === 0) {
return [];
}
return array_map(fn (int $cents) => (int) round($cents * 100 / $grand), $totals);
}
$expenses = [
['title' => 'Noodles', 'category' => 'food', 'cents' => 350],
['title' => 'Bus pass', 'category' => 'transport', 'cents' => 1200],
['title' => 'Cinema', 'category' => 'fun', 'cents' => 825],
['title' => 'Rice', 'category' => 'food', 'cents' => 475],
];
$top = topCategories($expenses, 2);
foreach (shareOfTotal($top) as $category => $percent) {
echo str_pad($category, 10) . $top[$category] . " cents $percent%\n";
}
echo 'limit 0: ' . json_encode(topCategories($expenses, 0)) . "\n";
echo 'no data: ' . json_encode(topCategories([], 3)) . "\n";
echo 'share of nothing: ' . json_encode(shareOfTotal([])) . "\n";
try {
topCategories($expenses, -1);
} catch (InvalidArgumentException $e) {
echo 'error: ' . $e->getMessage() . "\n";
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Give each layer one job: input checking, the domain model, the repository, the report
- Turn raw input into typed objects at the edge, reject bad data with exceptions, and wrap each row in its own try/catch
- Store money as whole cents
- Learn Composer, PHPUnit, security and a framework one at a time, each with its own project
Migrating to PHP 8.5 — PHP Documentation Group