Understanding MVC Architecture

The MVC pattern divides an application into three interconnected components:

  1. Model: Represents the data and the business logic of the application. It interacts with the database and handles data processing.
  2. View: Represents the user interface. It displays data from the model to the user and sends user commands to the controller.
  3. Controller: Acts as an intermediary between the Model and View. It processes user input, interacts with the model, and updates the view.

Directory Structure

Before we dive into coding, let’s define a simple directory structure for our MVC application:

/my_mvc_app
|-- /app
|   |-- /controllers
|   |-- /models
|   |-- /views
|-- /public
|   |-- index.php
|-- /config
|   |-- config.php

Step 1: Setting Up Configuration

Create a configuration file to manage database connections and other settings. In /config/config.php, add the following code:

<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'my_database');
define('DB_USER', 'root');
define('DB_PASS', 'password');

function getDbConnection() {
    try {
        $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $pdo;
    } catch (PDOException $e) {
        echo "Connection failed: " . $e->getMessage();
    }
}
?>

Step 2: Creating the Model

Create a model that interacts with the database. In /app/models/User.php, we will create a simple User model:

<?php
require_once __DIR__ . '/../../config/config.php';

class User {
    private $db;

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

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

Step 3: Creating the Controller

Next, we will create a controller that handles the user requests. In /app/controllers/UserController.php, add the following code:

<?php
require_once __DIR__ . '/../models/User.php';

class UserController {
    private $userModel;

    public function __construct() {
        $this->userModel = new User();
    }

    public function index() {
        $users = $this->userModel->getAllUsers();
        require_once __DIR__ . '/../views/user/index.php';
    }
}
?>

Step 4: Creating the View

Now, let’s create a view to display the user data. In /app/views/user/index.php, add the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User List</title>
</head>
<body>
    <h1>User List</h1>
    <table>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
        </tr>
        <?php foreach ($users as $user): ?>
        <tr>
            <td><?php echo htmlspecialchars($user['id']); ?></td>
            <td><?php echo htmlspecialchars($user['name']); ?></td>
            <td><?php echo htmlspecialchars($user['email']); ?></td>
        </tr>
        <?php endforeach; ?>
    </table>
</body>
</html>

Step 5: Setting Up the Entry Point

Finally, we need to set up the entry point for our application. In ../../../index.php, add the following code:

<?php
require_once __DIR__ . '/../app/controllers/UserController.php';

$controller = new UserController();
$controller->index();
?>

Running the Application

  1. Ensure you have a running web server (like Apache or Nginx) and PHP installed.
  2. Create a database named my_database and a table named users with appropriate fields (e.g., id, name, email).
  3. Place your application in the web server's root directory.
  4. Navigate to http://localhost/my_mvc_app/public in your browser.

Conclusion

This tutorial provided a foundational understanding of how to build a simple MVC framework in PHP. You learned about the structure, created models, controllers, and views, and set up a basic application. As you continue to develop your application, consider implementing features such as routing, error handling, and user authentication to enhance its functionality.

Learn more with useful resources