← Back to PHP Course | Chapter 14: Advanced PHP | Lesson 10 of 24

PHP MVC Architecture

What is MVC?

MVC splits an application into three responsibilities -- Model (data and business rules), View (presentation), and Controller (request handling) -- so a change to how data is displayed doesn't require touching how it's stored or validated.

Example: What is MVC?

php
<?php
class UserModel {
    function getName() { return "Alice"; }
}
class UserView {
    function render($name) { echo "<p>Name: $name</p>"; }
}
class UserController {
    function show() {
        $model = new UserModel();
        $view = new UserView();
        $view->render($model->getName());
    }
}
(new UserController())->show();
?>

The Model Layer

The Model layer owns your data: it talks to the database, enforces business rules, and knows nothing about HTML or HTTP, which keeps your data logic reusable outside of any one web request.

Example: The Model Layer

php
<?php
class UserModel {
    function findById($id) {
        return ["id" => $id, "name" => "Alice"];
    }
}
$model = new UserModel();
print_r($model->findById(1));
?>

The Controller Layer

The Controller receives an incoming request, asks the appropriate Model for data, and decides which View should render the response -- it's the coordination layer, not where business logic or markup belongs.

Example: The Controller Layer

php
<?php
class UserModel {
    function find($id) { return ["name" => "Alice"]; }
}
class UserController {
    function show($id) {
        $model = new UserModel();
        $data = $model->find($id);
        echo "Rendering view with: " . $data['name'];
    }
}
(new UserController())->show(1);
?>

The View Layer

The View layer's only job is presentation: it takes data the Controller hands it and renders it into HTML, ideally without containing any real logic beyond loops and conditionals for display.

Example: The View Layer

php
<?php
class UserView {
    function render($data) {
        foreach ($data as $key => $value) {
            echo "$key: $value\n";
        }
    }
}
(new UserView())->render(["name" => "Alice", "age" => 30]);
?>

Routing in MVC

A router examines the incoming URL and decides which Controller action should handle it, which is what lets an MVC app expose clean, predictable URLs like /users/5/edit instead of raw script paths.

Example: Routing in MVC

php
<?php
$url = "/users/5/edit";
if (preg_match('#^/users/(\d+)/edit$#', $url, $matches)) {
    echo "Routing to UserController::edit(" . $matches[1] . ")";
}
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.