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>