
To maintain code structure and improve sustainability in web applications, the MVC (Model-View-Controller) architecture is commonly used. MVC separates an application into three layers: Model (Data Management), View (Interface), and Controller (Business Logic), making the code more readable and maintainable.
Let’s create a simple MVC structure using PHP and understand how it works with a basic example. We'll build the core layers of a web application: Router, Controller, Model, and View. In real-world projects, MVC structures can become more complex, but the core principle is the separation of Model, View, and Controller.
1. Advantages of Using MVC
- ✅ Organized Code: Separates logic, data, and UI for a cleaner structure.
- ✅ Reusability: Components can be reused across multiple pages.
- ✅ Scalability: Easier to add new features by separating concerns.
- ✅ Maintainability: Update one part without breaking others.
- ✅ Testability: Each component can be tested independently.
2. MVC Folder Structure
Create the following directory structure to follow MVC principles:
/mvc_project
|-- app
| |-- controllers
| | |-- HomeController.php
| |-- models
| | |-- User.php
| |-- views
| | |-- home.php
|-- public
| |-- index.php
|-- core
| |-- Router.php
|-- config
| |-- config.php
|-- .htaccess
Use a .htaccess
file to route all requests to public/index.php
:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ public/index.php?url=$1 [QSA,L]
3. Coding the MVC Structure
3.1. Entry Point (public/index.php)
require_once '../core/Router.php';
$router = new Router();
$router->run();
3.2. Router Class (core/Router.php)
<?php
class Router {
public function run() {
$url = isset($_GET['url']) ? rtrim($_GET['url'], '/') : 'home';
$controllerName = ucfirst($url) . 'Controller';
$controllerFile = '../app/controllers/' . $controllerName . '.php';
if (file_exists($controllerFile)) {
require_once $controllerFile;
$controller = new $controllerName();
$controller->index();
} else {
http_response_code(404);
echo '404 - Page Not Found';
}
}
}
3.3. Controller (app/controllers/HomeController.php)
<?php
class HomeController {
public function index() {
require_once '../app/models/User.php';
$user = new User();
$data = $user->getUsers();
require_once '../app/views/home.php';
}
}
3.4. Model (app/models/User.php)
<?php
class User {
private $db;
public function __construct() {
$this->db = new PDO('mysql:host=localhost;dbname=mvc_project', 'root', '');
}
public function getUsers() {
$stmt = $this->db->query('SELECT id, name FROM users');
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
3.5. View (app/views/home.php)
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Users</h1>
<ul>
<?php foreach ($data as $user) { ?>
<li><?php echo htmlspecialchars($user['name']); ?></li>
<?php } ?>
</ul>
</body>
</html>
4. Running the MVC Project
Visit the following URL in your browser to test:
http://localhost/mvc_project/public/home
If everything works, you should see a list of Users.
5. Security & Development Tips
- 🔹 Database Connection: Use PDO for secure and dynamic DB access.
- 🔹 Use an ORM: Implement Eloquent or Doctrine to enhance model power.
- 🔹 CSRF Protection: Secure forms with CSRF tokens.
- 🔹 Advanced Routing: Add RESTful and flexible routing mechanisms.
- 🔹 Input Sanitization: Clean user input with
htmlspecialchars()
andfilter_input()
. - 🔹 Error Handling: Use
try-catch
blocks and custom error pages.
Related Articles
