0Pricing
PHP Academy · Lesson

Template Pattern: Separating Logic from View

Move business logic to PHP files and keep HTML templates clean.

Why Separate Logic from View?

Mixing database queries, business logic, and HTML in the same file leads to:

  • Hard-to-read spaghetti code
  • Difficulty testing and reusing logic
  • Security mistakes when validation is skipped

The solution: keep each concern in its own layer.

The Simple Template Pattern

Run all PHP logic first, then output HTML:

<?php
// --- LOGIC (top) ---
require 'config.php';
$userId = (int) ($_GET['id'] ?? 0);
$user   = getUserById($userId);
if (!$user) {
    http_response_code(404);
    require '404.php';
    exit;
}
$pageTitle = 'Profile: ' . $user['name'];

// --- VIEW (bottom) ---
require 'layout/header.php';
?>
<main>
    <h1><?= htmlspecialchars($user['name']) ?></h1>
</main>
<?php require 'layout/footer.php'; ?>

All lessons in this course

  1. PHP Tags and Embedding Syntax
  2. Dynamic HTML with PHP Loops
  3. Including and Requiring Files
  4. Template Pattern: Separating Logic from View
← Back to PHP Academy