EthicsComputerCourses
Join training +91 90532 10052

Organising Code: A Simple MVC

LAMP Stack · Lesson 9 of 20 Intermediate 10 min read Updated

By the end of this lesson ShikshaPortal's 215-line public/index.php will be a 58-line route table. SQL will live in model classes, request handling in controller classes, and HTML stays in templates. A small router class will answer unknown pages with 404 and wrong methods with 405. Every page will behave exactly as before, and you will know where each new piece of code belongs.

What you should know first: A Simple MVC Router builds a router from zero, and Dependency Injection & Containers explains passing objects into constructors. You also need the Composer setup from Composer & Autoloading, because every new class is found by PSR-4.

One file doing every job

Open public/index.php after the last three lessons. It reads the URL, checks the login, validates forms, catches database errors and chooses templates, for fifteen routes. It works, but the next feature (marks entry, uploads, a JSON API) would push it past 400 lines. Two people cannot edit it without clashing.

Picture a small school where one person is the gatekeeper, the class teacher, the record-room clerk and the notice-board writer. It works with fifty students. With five hundred, you hire people for each job. MVC (Model, View, Controller) does the same for code:

PartIts one jobIn ShikshaPortal
ModelData and the rules about it: SQL, validation, calculationssrc/Models/
ViewTurning data into HTMLtemplates/
ControllerReading the request, asking models, choosing a viewsrc/Controllers/
RouterChoosing the controller method for a URLsrc/Http/Router.php

A request now flows like this:

Text
Browser: POST /students/new
  -> public/index.php     start session, build the router
  -> Router               "POST /students/new" -> StudentController::store
  -> StudentController    require_login('admin'), validate $_POST
       -> StudentValidator   the school's rules
       -> StudentRepository  INSERT with a prepared statement
  -> redirect, or render('students/form') with the errors

The rule to remember: models never read $_POST or print HTML, views never run SQL, and controllers stay thin. If a controller method grows long, some of it is really model logic.

Step 1: the new layout

Here is src/ and templates/ after the change. Nothing outside these folders moves.

Text
src/
  bootstrap.php                 unchanged
  helpers.php, db.php, auth.php still plain functions, loaded by Composer "files"
  Controllers/
    HomeController.php          home(), about()
    ClassController.php         index(), show()
    StudentController.php       index(), show(), create(), store(), edit(), update(), leave(), destroy()
    AuthController.php          showLogin(), login(), logout()
  Http/
    Router.php
  Models/
    ClassRepository.php         all(), find(), options()
    StudentRepository.php       search(), find(), insert(), update(), markLeft(), delete()
    MarkRepository.php          saveForExam()
    StudentValidator.php        validate()
    ReportCard.php              moved from src/ReportCard.php
templates/
  layout.php, home.php, about.php, error.php
  auth/login.php
  classes/index.php, classes/show.php
  students/index.php, students/show.php, students/form.php

A repository is a class that holds all the SQL for one table, so the rest of the app asks it for data by name, such as $students->find(5), instead of writing queries. Templates moved into one folder per controller, so render('students/form', ...) reads clearly.

src/students.php and src/marks.php are gone; their functions became repository methods. Remove those two lines from the files list in composer.json, then run composer dump-autoload. The Shiksha\ rule already covers every new class, so nothing else needs adding.

Step 2: models take their database connection

Here is the start of src/Models/StudentRepository.php. The function bodies from the CRUD lesson moved in almost unchanged; only db() became $this->pdo:

PHP
<?php
declare(strict_types=1);

namespace Shiksha\Models;

use PDO;

/** Every SQL query about students lives here, and nowhere else. */
final class StudentRepository
{
    public function __construct(private readonly PDO $pdo)
    {
    }

    public function find(int $id): ?array
    {
        $stmt = $this->pdo->prepare(
            'SELECT s.*, c.grade, c.section
               FROM students s
               JOIN classes c ON c.id = s.class_id
              WHERE s.id = :id'
        );
        $stmt->execute(['id' => $id]);
        return $stmt->fetch() ?: null;
    }

    public function markLeft(int $id): void
    {
        $stmt = $this->pdo->prepare("UPDATE students SET status = 'left' WHERE id = :id");
        $stmt->execute(['id' => $id]);
    }

    // search(), insert(), update() and delete() follow the same pattern
}

Two details. use PDO; is needed because inside namespace Shiksha\Models, a bare PDO would mean Shiksha\Models\PDO. And the repository receives its connection through the constructor instead of calling db() itself. This is dependency injection: the object is handed what it needs, rather than fetching it.

The payoff is that a repository works with any PDO connection. This throwaway script gives StudentRepository an in-memory SQLite database with two rows, and the real class runs against it:

PHP
$pdo = new PDO('sqlite::memory:', null, null, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
// ... CREATE TABLE classes, students and INSERT two students of Class 10-A ...

$students = new StudentRepository($pdo);
foreach ($students->search(3, 'aarav') as $row) {
    echo "{$row['admission_no']} {$row['full_name']} {$row['grade']}-{$row['section']}\n";
}
Output
SP-2026-0031 Aarav Srivastava 10-A

That is the starting point of automated tests, which Testing with PHPUnit builds on. validate_student() became the static method StudentValidator::validate(), and ReportCard moved into Shiksha\Models because report-card maths is a school rule. Moving a class changes its full name, so update every use line. We forgot bin/report-card.php at first and got this (path shortened):

Output
PHP Fatal error:  Uncaught Error: Class "Shiksha\ReportCard" not found in ...\bin\report-card.php:28

The fix was one line: use Shiksha\Models\ReportCard;.

Step 3: controllers handle the request

Each closure from $routes became a method. Here is part of src/Controllers/StudentController.php:

PHP
<?php
declare(strict_types=1);

namespace Shiksha\Controllers;

use PDOException;
use Shiksha\Models\ClassRepository;
use Shiksha\Models\StudentRepository;
use Shiksha\Models\StudentValidator;

final class StudentController
{
    public function __construct(
        private readonly StudentRepository $students,
        private readonly ClassRepository $classes,
    ) {
    }

    public function store(): void
    {
        require_login('admin');
        [$data, $errors] = StudentValidator::validate($_POST, array_keys($this->classes->options()));
        if ($errors === []) {
            try {
                $id = $this->students->insert($data);
                flash('Student added.');
                redirect('/student?id=' . $id);
            } catch (PDOException $e) {
                $errors = $this->duplicateError($e);
            }
        }
        http_response_code(422);
        $this->form('Add a student', '/students/new', $data, $errors);
    }

    /** The student named by ?id=, or null after sending a 404 page. */
    private function studentFromQuery(): ?array
    {
        $id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
        $student = is_int($id) ? $this->students->find($id) : null;
        if ($student === null) {
            http_response_code(404);
            render('error', ['title' => 'Not found', 'message' => 'No student has that id.']);
        }
        return $student;
    }

    // index(), show(), create(), edit(), update(), leave(), destroy(), form(), duplicateError() ...
}

Read store() from top to bottom: check the user, validate, save, redirect, or show the form again. That is all a controller method should say. The repeated parts from the old closures (finding the student by ?id=, rendering the form, turning SQLSTATE 23000 into a message) became small private methods, which the router cannot call from a URL.

Functions such as require_login(), render() and flash() still come from src/auth.php and src/helpers.php. PHP looks for an unknown function first in the current namespace (Shiksha\Controllers\render), then falls back to the global one, so they work inside controllers with no use line. Classes do not fall back, which is why PDOException needs use.

Step 4: a router and a short front controller

src/Http/Router.php keeps the idea of the old $routes lookup and adds one improvement: if the path exists but the method does not, it answers 405 Method Not Allowed with an Allow header, instead of a misleading 404.

PHP
final class Router
{
    public function __construct(
        private readonly array $routes,    // 'GET /path' => [Controller::class, 'method']
        private readonly array $factories, // Controller::class => fn() => new Controller(...)
    ) {
    }

    public function dispatch(string $method, string $path): void
    {
        $route = $this->routes["{$method} {$path}"] ?? null;

        if ($route === null) {
            $allowed = $this->methodsFor($path); // e.g. ['GET'] for '/classes'
            if ($allowed !== []) {
                http_response_code(405);
                header('Allow: ' . implode(', ', $allowed));
                render('error', ['title' => 'Method not allowed', 'message' => 'This page does not accept that kind of request.']);
                return;
            }
            http_response_code(404);
            render('error', ['title' => 'Not found', 'message' => 'We could not find that page.']);
            return;
        }

        [$class, $action] = $route;
        $controller = ($this->factories[$class])();
        $controller->$action();
    }
}

methodsFor() is a private loop over the route keys that collects the methods whose path matches. Now public/index.php:

PHP
<?php
declare(strict_types=1);

use Shiksha\Controllers\AuthController;
use Shiksha\Controllers\ClassController;
use Shiksha\Controllers\HomeController;
use Shiksha\Controllers\StudentController;
use Shiksha\Http\Router;
use Shiksha\Models\ClassRepository;
use Shiksha\Models\StudentRepository;

require dirname(__DIR__) . '/src/bootstrap.php';

start_session();

// Which controller method answers each request
$routes = [
    'GET /'                => [HomeController::class, 'home'],
    'GET /about'           => [HomeController::class, 'about'],
    'GET /classes'         => [ClassController::class, 'index'],
    'GET /class'           => [ClassController::class, 'show'],
    'GET /students'        => [StudentController::class, 'index'],
    'GET /students/new'    => [StudentController::class, 'create'],
    'POST /students/new'   => [StudentController::class, 'store'],
    'GET /student'         => [StudentController::class, 'show'],
    'GET /student/edit'    => [StudentController::class, 'edit'],
    'POST /student/edit'   => [StudentController::class, 'update'],
    'POST /student/leave'  => [StudentController::class, 'leave'],
    'POST /student/delete' => [StudentController::class, 'destroy'],
    'GET /login'           => [AuthController::class, 'showLogin'],
    'POST /login'          => [AuthController::class, 'login'],
    'POST /logout'         => [AuthController::class, 'logout'],
];

// How to build each controller; only the one this request needs is created
$factories = [
    HomeController::class    => fn() => new HomeController(),
    AuthController::class    => fn() => new AuthController(),
    ClassController::class   => fn() => new ClassController(new ClassRepository(db())),
    StudentController::class => fn() => new StudentController(
        new StudentRepository(db()),
        new ClassRepository(db()),
    ),
];

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';

try {
    (new Router($routes, $factories))->dispatch($method, $path);
} catch (PDOException $e) {
    error_log('ShikshaPortal database error: ' . $e->getMessage());
    http_response_code(500);
    render('error', ['title' => 'Something went wrong', 'message' => 'Please try again in a few minutes.']);
}

$routes keeps the same 'METHOD /path' keys you already know, so the whole site map fits on one screen. HomeController::class is the class's full name as a string, checked by PHP and by editors, which is safer than typing 'Shiksha\Controllers\HomeController' by hand. The $factories closures only run when needed, so the home page never opens a database connection. The security rule is that the router calls only methods listed in $routes; never build a method name from the URL, or a visitor could call any public method.

The rule is easy to try in the browser. This page copies four of the routes and runs the router's lookup in JavaScript:

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Router check</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    td, th { border: 1px solid #999; padding: 4px 8px; text-align: left; }
    table { border-collapse: collapse; }
  </style>
</head>
<body>
  <h1>Which controller answers?</h1>
  <table>
    <thead><tr><th>Request</th><th>Status</th><th>Answer</th></tr></thead>
    <tbody id="rows"></tbody>
  </table>
  <script>
    const routes = {
      "GET /classes": "ClassController::index",
      "GET /students/new": "StudentController::create",
      "POST /students/new": "StudentController::store",
      "POST /student/delete": "StudentController::destroy"
    };
    const requests = ["GET /classes", "POST /classes", "POST /students/new", "GET /student/delete", "GET /teachers"];
    for (const request of requests) {
      const path = request.split(" ")[1];
      let status = "200";
      let answer = routes[request];
      if (!answer) {
        const allowed = Object.keys(routes).filter((key) => key.split(" ")[1] === path).map((key) => key.split(" ")[0]);
        status = allowed.length ? "405" : "404";
        answer = allowed.length ? "Allow: " + allowed.join(", ") : "Not found page";
      }
      const tr = document.createElement("tr");
      for (const text of [request, status, answer]) {
        const td = document.createElement("td");
        td.textContent = text;
        tr.append(td);
      }
      document.querySelector("#rows").append(tr);
    }
  </script>
</body>
</html>

Step 5: prove nothing broke

A refactor changes the shape of code, not its behaviour, so test every route before and after. Logged in as Neha (admin), our test copy answered:

Output
GET / 200
GET /classes 200
GET /class?id=3 200
GET /students?class_id=3 200
GET /student?id=5 200
GET /student/edit?id=5 200
GET /students/new 200
POST /student/delete?id=5 409
GET /missing 404
POST /classes 405
GET /student/delete?id=5 405

Every answer matches the last lesson except the final two, which used to be 404. They are the router's new 405 replies, and the raw response says which method is allowed:

Output
HTTP/1.1 405 Method Not Allowed
Allow: GET
        <h1>Method not allowed</h1>

What changed for later lessons

If you are following along, these are the changes to carry forward:

  • Routes map 'METHOD /path' to [Controller::class, 'method']; add new pages by adding a controller method and one line here.
  • SQL goes in a repository under src/Models/, which receives PDO in its constructor.
  • render() takes a template path such as 'students/index'.
  • helpers.php, db.php and auth.php are still global functions loaded through Composer's files list.
  • The ReportCard class is now Shiksha\Models\ReportCard.

Common mistakes

  • SQL inside controllers or templates. It spreads queries everywhere. Keep it in repositories.
  • Repositories reading $_POST or calling render(). Models must not know about HTTP or HTML.
  • Forgetting use PDO; inside a namespace. PHP then looks for Shiksha\Models\PDO.
  • Building the method name from the URL ($controller->{$_GET['action']}()). Visitors could call any public method.
  • Moving classes without updating use lines. Search the project for the old name.

Interview questions

1. What belongs in the model, the view and the controller?

The model holds data access and business rules, such as SQL, validation and report-card maths. The view turns data into HTML. The controller reads the request, calls the model, and picks a view or a redirect; it should stay short.

2. What is dependency injection, and why pass PDO into a repository?

Dependency injection means giving an object the things it needs, usually through its constructor, instead of letting it create or fetch them. A repository that receives PDO can be used with a test database, a different connection, or a mock, without changing its code.

3. When should a router return 405 instead of 404?

404 means no resource exists at that path. 405 means the path exists but does not accept the request method, for example a GET to a URL that only accepts POST. A 405 response must include an Allow header listing the accepted methods.

4. Why do global functions work inside a namespaced class without use, but classes do not?

For an unqualified function call, PHP first checks the current namespace and then falls back to the global function. Class names have no fallback, so a class from another namespace, or a global class like PDO, must be imported with use or written with a leading backslash.

Key points

  • MVC splits code by job: models for data and rules, views for HTML, controllers for requests.
  • Repositories hold all SQL for a table and receive PDO through their constructor.
  • Controllers check the user, call models, then redirect or render; repeated steps become private methods.
  • The router maps 'METHOD /path' to a controller method and answers 404 or 405 with Allow.
  • public/index.php is now a readable site map plus the factories that build controllers.
  • Test every route after a refactor; only the intended changes should appear.

Exercise

Add a subjects section the MVC way. Create Shiksha\Models\SubjectRepository with all() and find(int $id), and Shiksha\Controllers\SubjectController with index() and show() that render templates/subjects/index.php and templates/subjects/show.php. Register GET /subjects and GET /subject in $routes, add a factory, and check that POST /subjects returns 405.

Show solution
PHP
<?php
// src/Models/SubjectRepository.php
declare(strict_types=1);

namespace Shiksha\Models;

use PDO;

final class SubjectRepository
{
    public function __construct(private readonly PDO $pdo)
    {
    }

    public function all(): array
    {
        return $this->pdo->query('SELECT id, code, name FROM subjects ORDER BY name')->fetchAll();
    }

    public function find(int $id): ?array
    {
        $stmt = $this->pdo->prepare('SELECT id, code, name FROM subjects WHERE id = :id');
        $stmt->execute(['id' => $id]);
        return $stmt->fetch() ?: null;
    }
}
PHP
<?php
// src/Controllers/SubjectController.php
declare(strict_types=1);

namespace Shiksha\Controllers;

use Shiksha\Models\SubjectRepository;

final class SubjectController
{
    public function __construct(private readonly SubjectRepository $subjects)
    {
    }

    public function index(): void
    {
        render('subjects/index', ['title' => 'Subjects', 'subjects' => $this->subjects->all()]);
    }

    public function show(): void
    {
        $id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
        $subject = is_int($id) ? $this->subjects->find($id) : null;
        if ($subject === null) {
            http_response_code(404);
            render('error', ['title' => 'Not found', 'message' => 'No subject has that id.']);
            return;
        }
        render('subjects/show', ['title' => $subject['name'], 'subject' => $subject]);
    }
}

In public/index.php, add 'GET /subjects' => [SubjectController::class, 'index'], 'GET /subject' => [SubjectController::class, 'show'], the two use lines, and the factory SubjectController::class => fn() => new SubjectController(new SubjectRepository(db())). POST /subjects then gets 405 with Allow: GET, because the path exists only for GET.

Quick Quiz

1. Where should the SQL for "active students of Class 10-A" live?

2. A visitor sends GET to /student/delete?id=5, which only has a POST route. What does the new router return?

3. Inside namespace Shiksha\Models, why does the repository need use PDO;?

4. Why are controllers built by closures in $factories instead of all at the start?

Learn LAMP Stack with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call