In web development, frameworks are essential for building scalable and maintainable applications. While there are many popular frameworks like Laravel and Symfony, building your own custom MVC (Model-View-Controller) framework can help deepen your understanding of PHP and how web frameworks operate. In this article, we’ll walk through the basic concepts and steps involved in creating a simple MVC framework from scratch using PHP.
MVC (Model-View-Controller) is a design pattern that separates an application into three interconnected components:
This separation of concerns makes it easier to manage code, improve scalability, and allow different team members to work on various aspects of an application.
The first step is to create a well-organized file structure for your framework. Here’s a simple structure:
/myMVCframework
/app
/controllers
/models
/views
/core
Controller.php
Model.php
View.php
/public
index.php
.htaccess
.htaccessThe .htaccess file will ensure that all requests are directed to index.php, which will handle the routing of your application.
.htaccess:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
This configuration directs all incoming requests to the index.php file, regardless of the URL.
Let’s create the basic functionality for the Controller, Model, and View.
core/Controller.php:
<?php
class Controller {
public function view($view, $data = []) {
require_once '../app/views/' . $view . '.php';
}
public function model($model) {
require_once '../app/models/' . $model . '.php';
return new $model();
}
}
This base Controller class allows us to load views and models. It will be extended by all specific controllers in the app/controllers directory.
core/Model.php:
<?php
class Model {
// Here you can define the database connection and methods to interact with the database
}
The Model.php will be used as the parent class for all models. For now, we’ll keep it simple, but later it can be extended to include database interactions.
core/View.php:
<?php
class View {
// This class will be responsible for rendering the views
}
The View.php class will handle the presentation layer of the application, such as rendering HTML and passing data from the controller to the view.
index.phpIn the public/index.php file, we will handle the routing and direct requests to the correct controller and action.
public/index.php:
<?php
// Include the core files
require_once '../core/Controller.php';
// Get the URL and split it into parts
$url = isset($_GET['url']) ? $_GET['url'] : null;
$url = rtrim($url, '/');
$url = filter_var($url, FILTER_SANITIZE_URL);
$url = explode('/', $url);
// Example: /home/index
$controller = !empty($url[0]) ? $url[0] : 'home'; // Default controller is 'home'
$method = isset($url[1]) ? $url[1] : 'index'; // Default method is 'index'
$params = array_slice($url, 2); // Any additional parameters
// Check if the controller exists
if (file_exists('../app/controllers/' . ucfirst($controller) . '.php')) {
require_once '../app/controllers/' . ucfirst($controller) . '.php';
$controller = new $controller();
// Check if the method exists
if (method_exists($controller, $method)) {
call_user_func_array([$controller, $method], $params);
} else {
echo 'Method not found!';
}
} else {
echo 'Controller not found!';
}
This script fetches the controller, method, and parameters from the URL, then loads and calls the appropriate controller and method.
Now that our core structure is in place, let’s create a simple controller and view to see our framework in action.
app/controllers/Home.php:
<?php
class Home extends Controller {
public function index() {
$data = ['title' => 'Welcome to My Custom MVC Framework'];
$this->view('home/index', $data);
}
}
app/views/home/index.php:
<!DOCTYPE html>
<html>
<head>
<title><?php echo $data['title']; ?></title>
</head>
<body>
<h1><?php echo $data['title']; ?></h1>
<p>This is a simple MVC framework built with PHP!</p>
</body>
</html>
When a user visits /home/index (or just /, since home/index is the default), the Home controller’s index method will be called, which loads the home/index.php view with the $data array passed from the controller.
We’ll now add a simple model to demonstrate how the MVC pattern works together.
app/models/User.php:
<?php
class User {
public function getUsers() {
return ['John', 'Jane', 'Doe'];
}
}
Update the controller to use this model:
app/controllers/Home.php:
<?php
class Home extends Controller {
public function index() {
$userModel = $this->model('User');
$users = $userModel->getUsers();
$data = [
'title' => 'Welcome to My Custom MVC Framework',
'users' => $users
];
$this->view('home/index', $data);
}
}
Update the view to display the users:
app/views/home/index.php:
<!DOCTYPE html>
<html>
<head>
<title><?php echo $data['title']; ?></title>
</head>
<body>
<h1><?php echo $data['title']; ?></h1>
<p>This is a simple MVC framework built with PHP!</p>
<h2>Users:</h2>
<ul>
<?php foreach($data['users'] as $user): ?>
<li><?php echo $user; ?></li>
<?php endforeach; ?>
</ul>
</body>
</html>
Now when you visit the home/index route, the users will be displayed.
Building your own custom MVC framework in PHP may seem challenging at first, but it’s a fantastic way to better understand the core concepts behind web development and frameworks in general. By following this guide, you now have a basic framework to build upon, and you can extend it to include more features like database connections, authentication, and routing.
Once you’ve mastered the fundamentals, you’ll have a deeper appreciation for frameworks like Laravel and Symfony, and you’ll be able to customize your projects to suit specific requirements.
Understanding the difference between PHP Sessions and Cookies
The Geolocation API allows a web application to access a user’s geographical location (latitude, longitude, and more), with…
1. What Is the Golden Ratio? The Golden Ratio, represented by the Greek letter φ (phi), is…
In CSS, combinators define relationships between selectors. Instead of selecting elements individually, combinators allow you to target elements based…
Below is a comprehensive, beginner-friendly, yet deeply detailed guide to Boolean Algebra, complete with definitions, laws,…
Debugging your own code is hard enough — debugging someone else’s code is a whole…
Git is a free, open-source distributed version control system created by Linus Torvalds.It helps developers: Learn how to…