Learn PHP MVC: A Comprehensive Guide with Detailed Examples
* Web 2.0 University is supported by it's audience. If you purchase through links on our site, we may earn an affiliate commision.
The Model-View-Controller (MVC) architecture is a popular design pattern used in web development to separate concerns and improve code organization. Learning PHP MVC can help you build scalable, maintainable web applications. This guide will introduce you to the MVC pattern and show you how to implement it in PHP with detailed examples.
What is MVC?
MVC stands for Model-View-Controller. It divides an application into three interconnected components:
- Model: Represents the data and business logic.
- View: Displays the data (user interface).
- Controller: Handles user input and interacts with the model to update the view.
Why Use MVC?
- Separation of Concerns: Each component has a distinct responsibility, making the code easier to manage and understand.
- Reusability: Code can be reused across different parts of the application.
- Maintainability: Changes in one component have minimal impact on others, simplifying maintenance.
Setting Up a Basic PHP MVC Framework
Let’s build a simple PHP MVC framework from scratch. We’ll create a basic web application that manages a list of users.
Step 1: Directory Structure
First, set up the directory structure for the MVC application:
myapp/
│
├── app/
│ ├── controllers/
│ │ └── UserController.php
│ ├── models/
│ │ └── User.php
│ └── views/
│ └── users/
│ ├── index.php
│ └── show.php
│
├── public/
│ ├── index.php
│ └── .htaccess
│
├── core/
│ ├── App.php
│ ├── Controller.php
│ └── Model.php
│
└── config/
└── config.php
Step 2: Configuration
Create the configuration file config/config.php
to define database connection details:
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'mvc_example');
?>
Step 3: Core Components
Create core components to handle routing, base controller, and base model.
core/App.php:
<?php
class App {
protected $controller = 'UserController';
protected $method = 'index';
protected $params = [];
public function __construct() {
$url = $this->parseUrl();
if (file_exists('../app/controllers/' . $url[0] . '.php')) {
$this->controller = $url[0];
unset($url[0]);
}
require_once '../app/controllers/' . $this->controller . '.php';
$this->controller = new $this->controller;
if (isset($url[1])) {
if (method_exists($this->controller, $url[1])) {
$this->method = $url[1];
unset($url[1]);
}
}
$this->params = $url ? array_values($url) : [];
call_user_func_array([$this->controller, $this->method], $this->params);
}
public function parseUrl() {
if (isset($_GET['url'])) {
return explode('/', filter_var(rtrim($_GET['url'], '/'), FILTER_SANITIZE_URL));
}
}
}
?>
core/Controller.php:
<?php
class Controller {
public function model($model) {
require_once '../app/models/' . $model . '.php';
return new $model();
}
public function view($view, $data = []) {
require_once '../app/views/' . $view . '.php';
}
}
?>
core/Model.php:
<?php
class Model {
protected $db;
public function __construct() {
$this->db = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASS);
}
}
?>
Step 4: Public Entry Point
Create the public entry point public/index.php
:
<?php
require_once '../config/config.php';
require_once '../core/App.php';
require_once '../core/Controller.php';
require_once '../core/Model.php';
$app = new App();
?>
Step 5: .htaccess for URL Rewriting
Create the .htaccess
file in the public
directory for URL rewriting:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
Step 6: Creating the Model
Create the User
model in app/models/User.php
:
<?php
class User extends Model {
public function getAllUsers() {
$stmt = $this->db->query("SELECT * FROM users");
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function getUserById($id) {
$stmt = $this->db->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
return $stmt->fetch(PDO::FETCH_ASSOC);
}
}
?>
Step 7: Creating the Controller
Create the UserController
in app/controllers/UserController.php
:
<?php
class UserController extends Controller {
public function index() {
$userModel = $this->model('User');
$users = $userModel->getAllUsers();
$this->view('users/index', ['users' => $users]);
}
public function show($id) {
$userModel = $this->model('User');
$user = $userModel->getUserById($id);
$this->view('users/show', ['user' => $user]);
}
}
?>
Step 8: Creating the Views
Create the index
view in app/views/users/index.php
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Users List</title>
</head>
<body>
<h1>Users List</h1>
<ul>
<?php foreach ($data['users'] as $user): ?>
<li>
<a href="/user/show/<?php echo $user['id']; ?>">
<?php echo $user['name']; ?>
</a>
</li>
<?php endforeach; ?>
</ul>
</body>
</html>
Create the show
view in app/views/users/show.php
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User Details</title>
</head>
<body>
<h1>User Details</h1>
<p>Name: <?php echo $data['user']['name']; ?></p>
<p>Email: <?php echo $data['user']['email']; ?></p>
<p>Age: <?php echo $data['user']['age']; ?></p>
</body>
</html>
Conclusion
In this guide, we’ve covered the basics of the MVC pattern and how to implement it in PHP. We set up a basic PHP MVC framework and created a simple application to manage a list of users. This architecture helps in organizing your code better, making it more maintainable and scalable.
By following these steps, you can build more complex applications using the MVC pattern, which is a fundamental skill for any web developer. Continue exploring and expanding your application by adding more features and improving the structure.
Further Reading
By understanding and implementing the MVC pattern in PHP, you’ll be well-equipped to build robust and scalable web applications.