php · level 2 · unit 7 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Small typed functions turn a script into an app.
Most web apps do the same few jobs again and again: read the request, validate it, save to the database, then show the results safely. Give each job its own small function with types, and the main part of your program reads like a to-do list.
Moving code into functions like this, without changing what it does, is called refactoring. Each function can be tested on its own, and a bad value meets a clear exception instead of a mystery.
A function can take the database object as an argument too. Its type declaration is PDO, the name of that kind of object.
<?php
function clean_title(array $form): string {
$title = trim($form["title"] ?? "");
if ($title === "") { throw new InvalidArgumentException("A task needs a title"); }
return $title;
}
function show_task(array $row): string {
return sprintf("#%d %s", $row["id"], htmlspecialchars($row["title"]));
}
$_POST = ["title" => " Buy <b>milk</b> "];
$task = ["id" => 1, "title" => clean_title($_POST)];
echo show_task($task) . "\n"; Good function names, like clean_title and show_task, explain the program before anyone reads the insides.
guess first
Two functions share one database. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
function add_task(PDO $db, string $title): void {
$db->prepare("INSERT INTO tasks (title) VALUES (?)")->execute([$title]);
}
function count_tasks(PDO $db): int {
return $db->query("SELECT COUNT(*) AS n FROM tasks")->fetch(PDO::FETCH_ASSOC)["n"];
}
$db = new PDO("sqlite::memory:");
$db->exec("CREATE TABLE tasks (id INTEGER PRIMARY KEY, title TEXT)");
add_task($db, "Water plants");
add_task($db, "Call Gran");
echo count_tasks($db) . " tasks\n";
your turn
Your turn. Add a task to the app.
Type a task title and run it. Then try a title made only of spaces, and one with a tag like <i>.
fix it
The refactored function lost its answer. Fix it.
- Read the TypeError: the return value must be of type array, but none was returned.
- Line 4 works out the titles, then throws them away. The function never hands them back.
- Put
returnat the start of line 4, then press run.
nailed it
you built a real app, piece by piece. :D
- Give each job its own small, typed function.
- Validate, save with placeholders, then escape on the way out.
- Throw clear exceptions and catch them where you can help.
new words in your collection
- refactor
This lesson isn’t saved. A free account remembers every lesson you finish.