MVC Architecture in PHP
In this lesson: Understand MVC architecture in PHP with folder structure, router and a tiny working example — explained simply.
What is MVC
MVC stands for Model, View, Controller — a way of organising an app by splitting it into three parts, each with one job. Instead of one giant file mixing database code, logic and HTML, MVC keeps them separate and tidy. Almost every modern PHP framework is built on this pattern.
Model (data)
The Model handles data — talking to the database and enforcing rules.
<?php
class UserModel {
public function getUser($id) {
// fetch from database (via PDO)
return ["id" => $id, "name" => "Aman"];
}
}
?>
Only the Model touches the database. Everything about "what the data is and how to get it" lives here, in one place.
View (display)
The View is what the user sees — the HTML, filled with data.
<!-- user_view.php -->
<h1>Welcome <?php echo $name; ?></h1>
The View only displays; it contains no database code and little logic. This means a designer can edit the look without touching the app's brains.
Controller (logic)
The Controller is the go-between: it takes the request, asks the Model for data, and picks a View.
<?php
class UserController {
public function show($id) {
$model = new UserModel();
$user = $model->getUser($id);
$name = $user["name"];
include "user_view.php"; // show the View
}
}
?>
The Controller holds the "what to do" logic but no SQL and no HTML — it coordinates the Model and the View.
How a request flows
- A user visits a URL like
/user/5. - The Controller receives it and reads the id (5).
- It asks the Model for user 5's data.
- It passes that data to the View.
- The View renders HTML, which is sent to the browser.
Each part did its own job — data, coordination, display — and stayed out of the others' way.
Why use MVC
- Separation. Change the layout without touching database code.
- Teamwork. A designer edits Views while a developer edits Models.
- Reuse. One Model can feed many Views.
- Maintainable. Bugs are easier to find when each part has one job.
Common mistakes
- Putting SQL in the Controller or View. Database code belongs only in the Model.
- Heavy logic in the View. Views should mostly display, not decide.
- A "fat" Controller doing everything. Move data work to the Model.
- Thinking you need a framework. MVC is a pattern you can apply in plain PHP.
Summary
- MVC splits an app into Model, View and Controller.
- Model = data and database; View = the HTML the user sees.
- Controller = the logic that connects Model and View.
- A request flows Controller → Model → View → browser.
- MVC keeps big projects organised and easy to maintain.
Next, load classes cleanly with autoloading, or organise them with namespaces.
