MVC (Model-View-Controller) is a design pattern used in software development to separate the application logic into three interconnected components. This separation helps manage complex applications by dividing responsibilities, improving modularity, and making the code easier to maintain and test. Here’s how MVC works in PHP:
1. Model
The Model represents the data and the business logic of the application. It handles data retrieval, storage, and updates, often interacting with a database.
Responsibilities:
- Manage data and business rules.
- Interact with the database (CRUD operations: Create, Read, Update, Delete).
- Process data before it is displayed by the View.
Example:
class UserModel {
private $db;
public function __construct($database) {
$this->db = $database;
}
public function getUser($id) {
$stmt = $this->db->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);
return $stmt->fetch();
}
public function createUser($data) {
$stmt = $this->db->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
return $stmt->execute([$data['name'], $data['email']]);
}
// More CRUD operations...
}
2. View
The View is responsible for rendering the user interface and presenting data to the user. It only displays information and does not contain any business logic.
Responsibilities:
- Display data provided by the Model.
- Render HTML templates and handle the presentation layer.
Example:
// user_view.php
<!DOCTYPE html>
<html>
<head>
<title>User Details</title>
</head>
<body>
<h1>User Details</h1>
<p>Name: <?= htmlspecialchars($user['name']) ?></p>
<p>Email: <?= htmlspecialchars($user['email']) ?></p>
</body>
</html>
3. Controller
The Controller acts as an intermediary between the Model and the View. It handles user input, processes it, and updates the Model or View accordingly.
Responsibilities:
- Receive input from the user.
- Interact with the Model to retrieve or manipulate data.
- Pass data to the View for rendering.
Example:
class UserController {
private $model;
public function __construct($model) {
$this->model = $model;
}
public function showUser($id) {
$user = $this->model->getUser($id);
include 'user_view.php';
}
public function createUser($data) {
$this->model->createUser($data);
header('Location: /users');
}
// More actions...
}
Putting It All Together
To implement an MVC pattern in PHP, follow these steps:
Set Up the Environment:
- Create a basic file structure:
models
, views
, controllers
, and index.php
.
- Set up a database connection.
Define the Model:
- Create a model class to handle database operations.
Create the Controller:
- Develop a controller class to handle user input and interact with the model.
- Define methods for different actions (e.g., show user, create user).
Design the View:
- Create view files to render the data provided by the controller.
- Use basic HTML templates.
Route Requests:
- Use a basic routing mechanism in
index.php
to map URLs to controller actions.
Example of a Basic Routing Mechanism:
// index.php
require 'models/UserModel.php';
require 'controllers/UserController.php';
$database = new PDO('mysql:host=localhost;dbname=testdb', 'root', '');
$model = new UserModel($database);
$controller = new UserController($model);
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['id'])) {
$controller->showUser($_GET['id']);
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
$controller->createUser($_POST);
} else {
// Default action or error handling
}
Frameworks
While you can implement MVC from scratch, using a PHP framework like Laravel, Symfony, or CodeIgniter can simplify the process and provide additional features and tools.
By following the MVC pattern, you can create organized, maintainable, and scalable PHP applications.