MVC Model in PHP

The Model-View-Controller (MVC) is a design pattern that separates an application into three interconnected components, promoting modularity and code reusability. It is widely used in PHP frameworks like Laravel, CodeIgniter, and Symfony.

Key Components of MVC

Model

  • Represents the application's data and business logic.
  • Handles database operations, validation, and rules.

View

  • Represents the UI or presentation layer.
  • Displays data to the user and collects input.

Controller

  • Acts as a bridge between the Model and View.
  • Processes user input, interacts with the Model, and updates the View.

How MVC Works

  1. The user sends a request (e.g., clicks a button or submits a form).
  2. The Controller handles the request, interacts with the Model for data, and prepares the response.
  3. The Model fetches or processes data.
  4. The Controller passes data to the View.
  5. The View generates the output (e.g., HTML page) for the user.

Simple MVC Example in PHP

Directory Structure

project/
├── controllers/
│   └── ProductController.php
├── models/
│   └── Product.php
├── views/
│   └── product_list.php
└── index.php

The Model (Product.php)

Handles data and business logic.

<?php
// models/Product.php
class Product {
    public static function getAllProducts() {
        // Simulate fetching data from a database
        return [
            ['id' => 1, 'name' => 'Laptop', 'price' => 1200],
            ['id' => 2, 'name' => 'Mouse', 'price' => 25],
            ['id' => 3, 'name' => 'Keyboard', 'price' => 45],
        ];
    }
}
?>

The Controller (ProductController.php)

Manages user requests and connects the Model with the View.

<?php
// controllers/ProductController.php
require_once 'models/Product.php';

class ProductController {
    public function listProducts() {
        // Fetch data from the Model
        $products = Product::getAllProducts();

        // Pass data to the View
        require 'views/product_list.php';
    }
}
?>

The View (product_list.php)

Displays the data to the user.

<!-- views/product_list.php -->
<!DOCTYPE html>
<html>
<head>
    <title>Product List</title>
</head>
<body>
    <h1>Product List</h1>
    <table border="1">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Price</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($products as $product): ?>
                <tr>
                    <td><?= $product['id'] ?></td>
                    <td><?= $product['name'] ?></td>
                    <td>$<?= $product['price'] ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</body>
</html>

The Entry Point (index.php)

Routes the request to the appropriate Controller.

<?php
// index.php
require_once 'controllers/ProductController.php';

$controller = new ProductController();
$controller->listProducts();
?>

Execution Flow

  1. User accesses index.php, which initializes the ProductController.
  2. The Controller calls the listProducts() method.
  3. The Model (Product) fetches data (e.g., from a database or an array).
  4. The View (product_list.php) renders the data as an HTML table.

Advantages of MVC

  1. Separation of Concerns: Each component has a specific responsibility, making the application modular.
  2. Reusability: Models and Views can be reused across different parts of the application.
  3. Maintainability: Easier to debug and update as components are loosely coupled.
  4. Scalability: Well-suited for large applications.