×

php · level 3 · unit 6 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

splits an app into data, display and decisions.

Most PHP frameworks follow MVC. The holds data and its rules: finding pets, refusing bad ones. The turns data into HTML and escapes every value. The sits between them: it reads the request, asks the model, then hands the answer to a view.

Each part has one job. You can change how pets look without touching how they are stored, and test the rules with no HTML at all. In a full app, the router from the last lesson picks which controller method runs.

<?php
class PetModel {
    public function kindOf(string $name): ?string { return ["rex" => "dog", "tom" => "cat"][$name] ?? null; }
}
function petView(string $name, string $kind): string {
    return "<h1>" . htmlspecialchars("$name the $kind", ENT_QUOTES) . "</h1>";
}
class PetController {
    public function __construct(private PetModel $model) {}
    public function show(array $query): string {
        $name = $query["name"] ?? "";
        return petView($name, $this->model->kindOf($name) ?? "mystery pet");
    }
}
$_GET = ["name" => "rex"];
echo (new PetController(new PetModel()))->show($_GET) . "\n";

The model never writes HTML and the view never touches data storage, so each can change on its own.