Table of Contents
- Introduction to MVC
- What is MVC?
- The Benefits of MVC Architecture
- The Core Components of MVC
- Model
- View
- Controller
- Building a Simple MVC Framework
- Setting Up the Project Structure
- Implementing the Model
- Creating the View
- Writing the Controller
- Routing and URL Mapping
- Practical Example: Building a Simple Blog Application
- Conclusion and Best Practices
Introduction to MVC
What is MVC?
MVC stands for Model-View-Controller, a software architectural pattern used to separate an application into three interconnected components. This separation allows for modular development, easier maintenance, and scalability. Here’s a breakdown of the three components:
- Model: Represents the data and business logic of the application. The model retrieves data, processes it, and sends it to the controller.
- View: Represents the user interface (UI) of the application. The view is responsible for displaying the data to the user in a meaningful way.
- Controller: Acts as the intermediary between the model and the view. It processes user input, manipulates the model, and updates the view.
The Benefits of MVC Architecture
- Separation of Concerns: By separating the application into three distinct components, it becomes easier to manage and update each part independently.
- Scalability: As the application grows, the structure remains organized, which is helpful for adding new features or updating existing ones.
- Maintainability: Since the application is modular, individual components can be modified without affecting the entire system.
The Core Components of MVC
Let’s take a closer look at the three main components of MVC.
1. Model
The Model represents the data of the application and the business rules that govern it. In PHP, this is typically where the database interaction occurs. The model is responsible for fetching, processing, and updating data. It doesn’t concern itself with how the data is displayed.
Example: User.php
Model
<?php
class User {
private $db;
public function __construct($db) {
$this->db = $db;
}
public function getAllUsers() {
$query = "SELECT * FROM users";
return $this->db->query($query);
}
public function getUserById($id) {
$query = "SELECT * FROM users WHERE id = :id";
$stmt = $this->db->prepare($query);
$stmt->execute([':id' => $id]);
return $stmt->fetch();
}
}
?>
2. View
The View is responsible for rendering the UI. It displays the data provided by the controller and may include HTML, CSS, and JavaScript. In PHP MVC applications, views are typically stored in separate files, such as .php
or .html
.
Example: user_list.php
View
<!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>Users</h1>
<ul>
<?php foreach ($users as $user): ?>
<li><?= $user['name']; ?> - <?= $user['email']; ?></li>
<?php endforeach; ?>
</ul>
</body>
</html>
3. Controller
The Controller manages user input, interacts with the model, and returns the appropriate view. The controller handles the logic of the application and determines which view to display based on the actions taken by the user.
Example: UserController.php
Controller
<?php
class UserController {
private $userModel;
public function __construct($userModel) {
$this->userModel = $userModel;
}
public function index() {
$users = $this->userModel->getAllUsers();
require_once 'views/user_list.php';
}
public function show($id) {
$user = $this->userModel->getUserById($id);
require_once 'views/user_detail.php';
}
}
?>
Building a Simple MVC Framework
Now that we understand the core components of MVC, let’s create a basic framework to implement this pattern in PHP. We’ll set up the project structure, create the model, view, and controller, and connect everything together.
Setting Up the Project Structure
Create the following directory structure for your MVC framework:
/mvc-framework
/controllers
UserController.php
/models
User.php
/views
user_list.php
user_detail.php
/core
Router.php
index.php
Router Class
In an MVC framework, the Router is responsible for mapping the URLs to the corresponding controller methods. Let’s create a simple router to handle basic URL routing.
<?php
class Router {
public function route($url) {
// Simple routing mechanism to route to controllers
$urlParts = explode('/', $url);
$controller = ucfirst($urlParts[0]) . 'Controller';
$method = $urlParts[1] ?? 'index'; // Default to 'index' method
$controllerFile = 'controllers/' . $controller . '.php';
if (file_exists($controllerFile)) {
require_once $controllerFile;
$controllerObj = new $controller(new User(new Database()));
if (method_exists($controllerObj, $method)) {
$controllerObj->$method();
} else {
echo "Method $method not found!";
}
} else {
echo "Controller $controller not found!";
}
}
}
?>
Database Class
To make the example work, let’s also include a simple Database
class that connects to the database.
<?php
class Database {
private $pdo;
public function __construct() {
$this->pdo = new PDO('mysql:host=localhost;dbname=mvc_framework', 'root', '');
}
public function query($sql) {
return $this->pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
}
public function prepare($sql) {
return $this->pdo->prepare($sql);
}
}
?>
index.php
The index.php
file serves as the entry point of the application. It initializes the router and handles incoming requests.
<?php
require_once 'core/Router.php';
require_once 'models/User.php';
require_once 'controllers/UserController.php';
require_once 'core/Database.php';
$router = new Router();
$url = $_GET['url'] ?? 'user/index'; // Default route
$router->route($url);
?>
Routing and URL Mapping
In this simple MVC framework, the routing is based on the URL structure. For example:
index.php/user/index
will call theindex()
method in theUserController
.index.php/user/show/1
will call theshow(1)
method in theUserController
to display the details of user with ID 1.
Example Usage:
- Navigate to
index.php/user/index
to view the list of users. - Navigate to
index.php/user/show/1
to view the details of the user with ID 1.
Practical Example: Building a Simple Blog Application
Let’s briefly discuss how this framework can be used to build a simple blog application. In the blog app, the controller will interact with the database to fetch blog posts, and the view will display them on the page.
The model (Post.php
) would handle fetching blog posts from the database, the controller (PostController.php
) would pass the data to the view, and the view (post_list.php
) would render the posts.
Conclusion and Best Practices
In this module, you learned how to create a simple MVC framework in PHP. We:
- Defined the roles of the Model, View, and Controller.
- Implemented the core components of MVC.
- Set up routing to map URLs to controller methods.
- Created a practical example to demonstrate the framework in action.
This simple MVC framework can serve as the foundation for building more complex PHP applications. As your application grows, you can enhance the framework by adding more features, such as middleware, authentication, and more advanced routing mechanisms.