📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHP for Beginners PHP MVC Pattern

PHP MVC Pattern

7 min read Quiz at the end
MVC splits your app into Model (data), View (display), and Controller (request handling). This separation keeps code organized and easy to maintain. All major PHP frameworks like Laravel are built on this pattern.

MVC Pattern in PHP

Model-View-Controller separates data, display, and logic.

// Model — data and database
class UserModel {
    public function __construct(private PDO $db) {}

    public function findById(int $id): ?array {
        $stmt = $this->db->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch() ?: null;
    }

    public function create(array $data): int {
        $stmt = $this->db->prepare("INSERT INTO users (name,email) VALUES (?,?)");
        $stmt->execute([$data["name"], $data["email"]]);
        return (int) $this->db->lastInsertId();
    }
}

// Controller — handles request/response
class UserController {
    public function __construct(private UserModel $model) {}

    public function show(int $id): void {
        $user = $this->model->findById($id);
        if (!$user) { http_response_code(404); return; }
        require "views/user_show.php";  // pass $user to view
    }
}

// View — views/user_show.php
// <h1><?= htmlspecialchars($user["name"]) ?></h1>
Topic Quiz · 5 questions

Test your understanding before moving on

1. What does MVC stand for?
💡 MVC is a design pattern: Model (data), View (display), Controller (logic).
2. What is the role of the Model?
💡 The Model handles data, database queries, and business rules.
3. What is the role of the View?
💡 The View handles presentation — generating HTML from data provided by the Controller.
4. What is the role of the Controller?
💡 The Controller receives requests, calls Models for data, and passes it to Views.
5. Why use MVC?
💡 MVC separates concerns, making code more maintainable, testable, and scalable.