0Pricing
PHP Academy · Lesson

Template Pattern: Separating Logic from View

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

Template Pattern: Separating Logic from View is a free PHP Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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'; ?>

Separating Controller and View Files

Split into a controller file and a view file:

// profile.php (controller)
<?php
require 'config.php';
$userId = (int) ($_GET['id'] ?? 0);
$user   = getUserById($userId);
$posts  = getPostsByUser($userId);

if (!$user) { require '404.php'; exit; }

require 'views/profile.view.php';

// views/profile.view.php (view) — only HTML and echoes
// No DB calls allowed here!

Prepare View Data

Format all data in the logic layer before sending to the view:

<?php
$user = getUserById($id);

$viewData = [
    'userName'   => htmlspecialchars($user['name']),
    'avatarUrl'  => $user['avatar'] ?? '/default.png',
    'joinedDate' => date('F Y', strtotime($user['created_at'])),
    'isAdmin'    => in_array('admin', $user['roles']),
];

extract($viewData);  // Makes $userName, $avatarUrl, etc.
require 'views/profile.view.php';

Template Function Pattern

Wrap view rendering in a function for cleaner reuse:

<?php
function render(string $view, array $data = []): void {
    extract($data);  // Create variables from array
    require __DIR__ . '/views/' . $view . '.php';
}

// Usage:
render('profile', [
    'name'   => $user['name'],
    'email'  => $user['email'],
]);

Output Buffering Template Engine

Render a template and return it as a string:

<?php
function renderToString(string $view, array $data = []): string {
    extract($data);
    ob_start();
    require __DIR__ . '/views/' . $view . '.php';
    return ob_get_clean();
}

$html = renderToString('email/welcome', ['name' => 'Alice']);
mail($to, 'Welcome!', $html, 'Content-Type: text/html');

When to Use a Template Engine

For simple sites, PHP's native templating is fine. Consider Twig or Blade when:

  • You want automatic escaping by default
  • Designers need to edit templates without PHP knowledge
  • You need template inheritance and macros
  • The project has many views and grows large

Twig Example

Twig (used by Symfony) provides clean syntax with automatic escaping:

<?php
// After: composer require twig/twig
$loader = new Twig\Loader\FilesystemLoader('/templates');
$twig   = new Twig\Environment($loader, ['cache' => '/tmp/twig']);

echo $twig->render('profile.html.twig', [
    'user'  => $user,
    'posts' => $posts,
]);

// profile.html.twig:
// <h1>{{ user.name }}</h1>  -- auto-escaped by default

MVC Directory Structure

A minimal MVC layout for plain PHP projects:

project/
  controllers/
    UserController.php   -- handles request, calls model
  models/
    User.php             -- database queries
  views/
    users/
      profile.php        -- display only, no logic
  public/
    index.php            -- front controller (router)

Front Controller Pattern

Route all requests through a single entry point:

<?php
// public/index.php (front controller)
require __DIR__ . '/../vendor/autoload.php';

$uri    = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$routes = require '../routes.php';

if (isset($routes[$uri])) {
    [$controller, $action] = $routes[$uri];
    (new $controller)->$action();
} else {
    http_response_code(404);
    require '../views/404.php';
}

Single Responsibility Principle

Each file should have one reason to change:

  • Model: only changes when data structure or query logic changes
  • Controller: only changes when request-handling logic changes
  • View: only changes when the UI or layout changes

This makes each piece easier to test and maintain independently.

Quick Check

What is the primary benefit of separating PHP logic from HTML view code?

Recap: Template Pattern

Key takeaways:

  • Run all logic first, then output HTML
  • Separate into controller and view files
  • Use a render() function with extract()
  • Output buffering captures rendered HTML
  • Consider Twig/Blade for larger projects
  • Front controller routes all requests to handlers

Frequently asked questions

Is the “Template Pattern: Separating Logic from View” lesson free?

Yes — the full text of “Template Pattern: Separating Logic from View” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.

What will I learn in “Template Pattern: Separating Logic from View”?

Move business logic to PHP files and keep HTML templates clean. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start PHP Academy?

No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Template Pattern: Separating Logic from View” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this PHP Academy lesson?

Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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