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
.htaccess
The .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.php
In 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
Amazon Web Services (AWS) continues to enhance its customer experience by offering more flexible payment…
JavaScript, often hailed as the "language of the web," continues to dominate the programming landscape…
Amazon is accelerating efforts to reinvent Alexa as a generative AI-powered “agent” capable of performing…
SpaceX's satellite-based Starlink, which is currently unlicensed for use in India, is reportedly being utilized…
Netflix, a pioneer in the streaming industry, has always been at the forefront of adopting…
Microsoft has announced legal action against a 'foreign-based threat actor group' accused of running a…