MVC Architecture in PHP


Introduction

The MVC (Model-View-Controller) architecture is a widely used software design pattern in web development. When working with PHP web applications, implementing the MVC pattern offers better separation of concerns, easier maintenance, and scalable code structure.

This article will walk you through the fundamentals of MVC in PHP, including its core components, how it works, a practical implementation, and MVC design pattern best practices in PHP.

What is MVC Architecture in PHP?

MVC architecture is a design pattern that separates the application into three major components:

  • Model – Handles data and business logic
  • View – Manages the presentation layer (HTML, CSS)
  • Controller – Acts as an intermediary between Model and View

Using MVC in PHP helps developers organize their code into modular and maintainable segments.

Why Use MVC in PHP?

Implementing the Model-View-Controller pattern in PHP has several benefits:

  • Clean code organization
  • Separation of logic and presentation
  • Improved scalability
  • Better code reusability
  • Team collaboration efficiency

High-traffic PHP applications and modern frameworks like Laravel, CodeIgniter, Symfony are built using this architecture.

Key Components of MVC Architecture

1. Model (Data Layer)

The Model handles everything related to data:

  • Connecting to the database
  • Fetching, inserting, updating, and deleting records
  • Applying business logic

Example (models/UserModel.php):

<?php
class UserModel {
    private $db;

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

    public function getUsers() {
        $query = "SELECT * FROM users";
        return $this->db->query($query)->fetchAll();
    }
}
?>

2. View (Presentation Layer)

The View is responsible for rendering data to the user:

  • Displays HTML templates
  • Retrieves data from the Controller

Example (views/users.php):

<h2>User List</h2>
<ul>
    <?php foreach ($users as $user): ?>
        <li><?php echo $user['name']; ?></li>
    <?php endforeach; ?>
</ul>

3. Controller (Application Logic)

The Controller is the brain of the MVC:

  • Accepts user input (from URL or forms)
  • Interacts with the Model
  • Passes data to the View

Example (controllers/UserController.php):

<?php
require_once 'models/UserModel.php';

class UserController {
    public function index() {
        $db = new PDO("mysql:host=localhost;dbname=mvc_demo", "root", "");
        $model = new UserModel($db);
        $users = $model->getUsers();
        include 'views/users.php';
    }
}
?>

How MVC Works in PHP – Flow Diagram

  1. User Request → URL like index.php?controller=user&action=index
  2. Router loads the appropriate controller
  3. Controller calls the Model
  4. Model returns data to Controller
  5. Controller passes data to View
  6. View renders HTML to the browser

Project Directory Structure

/mvc-app
│
├── index.php
├── controllers/
│   └── UserController.php
├── models/
│   └── UserModel.php
├── views/
│   └── users.php
└── config/
    └── database.php

Step-by-Step Example to Build a Simple MVC App in PHP

Step 1: Create the Front Controller (index.php)

<?php
$controller = $_GET['controller'] ?? 'user';
$action = $_GET['action'] ?? 'index';

require_once "controllers/" . ucfirst($controller) . "Controller.php";
$controllerClass = ucfirst($controller) . "Controller";
$controllerInstance = new $controllerClass();
$controllerInstance->$action();
?>

Step 2: Build the Model (UserModel.php)

<?php
class UserModel {
    private $pdo;

    public function __construct() {
        $this->pdo = new PDO("mysql:host=localhost;dbname=mvc_demo", "root", "");
    }

    public function getAllUsers() {
        $stmt = $this->pdo->query("SELECT * FROM users");
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}
?>

Step 3: Build the Controller (UserController.php)

<?php
require_once 'models/UserModel.php';

class UserController {
    public function index() {
        $model = new UserModel();
        $users = $model->getAllUsers();
        include 'views/users.php';
    }
}
?>

Step 4: Create the View (users.php)

<!DOCTYPE html>
<html>
<head>
    <title>User List</title>
</head>
<body>
    <h1>All Users</h1>
    <ul>
        <?php foreach($users as $user): ?>
            <li><?php echo htmlspecialchars($user['name']); ?></li>
        <?php endforeach; ?>
    </ul>
</body>
</html>

Best Practices for Using MVC in PHP

  • Keep controllers thin; move logic to models
  • Sanitize user input in controllers
  • Avoid business logic in views
  • Use PDO with prepared statements for database operations
  • Implement a simple routing mechanism
  • Organize files logically