PHP

Lesson 10

Separating logic from templates

Keep request handling and data access outside templates so rendering code stays small and easy to review.

Good Code

src/Controller/ProfileController.php
<?php declare(strict_types=1);

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

    public function show(int $userId): array
    {
        $user = $this->users->findProfile($userId);

        return [
            'title' => $user['name'],
            'user' => $user,
        ];
    }
}

Bad Code

profile.php
<?php

$userId = $_GET['id'];
$user = $pdo->query("SELECT * FROM users WHERE id = $userId")->fetch();
?>

<h1><?= $user['name'] ?></h1>
<p><?= $user['bio'] ?></p>

Review Notes

What to review

Good Code

The good version prepares a view model before rendering. The template can focus on display and escaping.

Bad Code

The bad version mixes request input, SQL, database access, and raw output in one file. Every change becomes a cross-cutting review.

Takeaways

  • Templates should render a prepared view model, not query databases or decide application flow.