Good Code
The good version prepares a view model before rendering. The template can focus on display and escaping.
Lesson 10
Keep request handling and data access outside templates so rendering code stays small and easy to review.
<?php declare(strict_types=1);
final class ProfileController
{
public function __construct(private UserRepository $users) {}
public function show(int $userId): array
{
// The controller prepares data before the template renders it.
$user = $this->users->findProfile($userId);
return [
'title' => $user['name'],
'user' => $user,
];
}
}<?php
// Request input, SQL, and output are mixed in one template file.
$userId = $_GET['id'];
$user = $pdo->query("SELECT * FROM users WHERE id = $userId")->fetch();
?>
<h1><?= $user['name'] ?></h1>
<p><?= $user['bio'] ?></p>The good version prepares a view model before rendering. The template can focus on display and escaping.
The bad version mixes request input, SQL, database access, and raw output in one file. Every change becomes a cross-cutting review.