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

PHP MVC Architecture

MVC splits a program into three helpers: one keeps the data, one shows the page, and one directs traffic. It is like a restaurant with a kitchen, a dining room, and a waiter.

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
// Define the class `UserModel`
class UserModel {
    // Define the function `getName` with no parameters
    function getName() { return "Alice"; }
}
// Define the class `UserView`
class UserView {
    // Define the function `render` taking `$name`
    function render($name) { echo "<p>Name: $name</p>"; }
}
// Define the class `UserController`
class UserController {
    // Define the function `show` with no parameters
    function show() {
        // Create a new `UserModel` instance, stored in `$model`
        $model = new UserModel();
        // Create a new `UserView` instance, stored in `$view`
        $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
// Define the class `UserModel`
class UserModel {
    // Define the function `findById` taking `$id`
    function findById($id) {
        // Return `["id" => $id, "name" => "Alice"]` from this function
        return ["id" => $id, "name" => "Alice"];
    }
}
// Create a new `UserModel` instance, stored in `$model`
$model = new UserModel();
// Print a human-readable dump of `$model->findById(1)`
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
// Define the class `UserModel`
class UserModel {
    // Define the function `find` taking `$id`
    function find($id) { return ["name" => "Alice"]; }
}
// Define the class `UserController`
class UserController {
    // Define the function `show` taking `$id`
    function show($id) {
        // Create a new `UserModel` instance, stored in `$model`
        $model = new UserModel();
        // Declare `$data`, set to `$model->find($id)`
        $data = $model->find($id);
        // Print `"Rendering view with: " . $data['name']` to the output
        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
// Define the class `UserView`
class UserView {
    // Define the function `render` taking `$data`
    function render($data) {
        // Loop over `$data`, binding each item to `$key => $value`
        foreach ($data as $key => $value) {
            // Print "$key: $value\n" to the output
            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
// Declare `$url`, set to "/users/5/edit"
$url = "/users/5/edit";
// Check whether `preg_match('#^/users/(\d+)/edit$#', $url, $matches)`
if (preg_match('#^/users/(\d+)/edit$#', $url, $matches)) {
    // Print "Routing to UserController::edit(" . $matches[1] . ")" to the output
    echo "Routing to UserController::edit(" . $matches[1] . ")";
}
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Putting SQL and business logic inside the view templates.
  2. Making the controller do everything, so it becomes huge and hard to maintain.
  3. Letting the model output HTML, which mixes data and presentation.

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.