Skip to content

How the MVC System works

Kyle Smith edited this page Jan 13, 2026 · 1 revision

The MVC splits the application into three layers

Below is a clean, practical walkthrough of how a PHP MVC (Model–View–Controller) system works, using a simple “User List” example. It’s not tied to any specific framework — just the core pattern so you can see the moving parts clearly.


🧩 Overview of MVC in PHP

A PHP MVC system splits your application into three layers:

Layer Responsibility
Model Talks to the database, handles data logic
View Displays HTML to the user
Controller Receives requests, calls the model, chooses the view

This separation keeps your code modular, testable, and easier to maintain.


🛠️ Example Scenario

We want a page that pulls basic information about a user

Directory structure:


   /controllers
       SampleController.php
   /models
       SampleModel.php
   /views
       SampleView.php
/public
   index.php

SampleController.php

<?php
namespace SkeletonPHP\Controllers;

use SkeletonPHP\Core\Container;

class SampleController {
    protected $container;

    public function __construct(Container $container) {
         $this->container = $container;
    }

    public function index() {
         // Retrieve the SampleModel instance from the container
         $model = $this->container->get('SampleModel');
         $data  = $model->sample_query();

         // Retrieve the HomeView instance and render the data
         $view = $this->container->get('SampleView');
         return $view->render($data);
    }
}
?>

SampleModel.php

<?php
namespace SkeletonPHP\Models;

class SampleModel {
    // This method emulates a data query.
    public function sample_query() {
         return [
             'name'  => 'John Doe',
             'email' => 'johndoe@example.com',
             'bio'   => 'Software developer with 10 years of experience.'
         ];
    }
}
?>

Sampleview.php

<?php
namespace SkeletonPHP\Views;

class SampleView {
    /**
     * Render the home page view.
     *
     * @param array $data Data to be rendered.
     */
    public function render($data) {
       echo "<h1>Home Page</h1>";
       if(is_array($data)) {
          echo "<ul>";
          foreach ($data as $key => $value) {
             echo "<li>" . htmlspecialchars($key) . " : " . htmlspecialchars($value) . "</li>";
          }
          echo "</ul>";
       } else {
           echo "No data to display.";
       }
    }
}
?>

Clone this wiki locally