php

Creating a Custom MVC Framework with PHP

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.

What is MVC?

MVC (Model-View-Controller) is a design pattern that separates an application into three interconnected components:

  • Model: The logic and data of the application. It handles database interactions, data validation, and business logic.
  • View: The presentation layer that displays data to users, typically in the form of HTML.
  • Controller: The intermediary between the Model and View. It processes user input and calls the necessary logic from the Model and updates the View accordingly.

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.


Step-by-Step Guide to Building a Custom MVC Framework

Step 1: Setting Up the File Structure

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
  • app/controllers: This folder will contain your application’s controllers.
  • app/models: This folder will store your application’s models, which represent the data and business logic.
  • app/views: This folder will contain the HTML templates and other UI elements that users see.
  • core: This folder will hold the core classes of your framework, such as the base controller, model, and view classes.
  • public/index.php: This is the entry point of the application. All requests will go through this file.

Step 2: Setting Up Routing in .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.

Step 3: Creating the Core Files (Controller, Model, and View)

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.

Step 4: Handling Routing and Requests in 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.

Step 5: Creating a Simple Controller and View

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.

Step 6: Adding a Model

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.


Conclusion

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

Author

Recent Posts

Hackers Exploiting Microsoft Teams to Remotely Access Users’ Systems

Hackers are exploiting Microsoft Teams to deceive users into installing remote access tools, granting attackers…

23 hours ago

Ethical Hacking Essentials

Data plays an essential role in our lives.  We each consume and produce huge amounts…

2 days ago

Thomas E. Kurtz, co-creator of the BASIC programming language, passes away at 96.

Thomas E. Kurtz, co-creator of the BASIC programming language, passed away on November 12, 2024,…

2 days ago

Mark Cuban believes AI will have minimal impact on jobs that demand critical thinking.

Mark Cuban recently expressed his views on the impact of artificial intelligence (AI) on the…

3 days ago

Free AI training data, courtesy of Harvard, OpenAI, and Microsoft

Harvard researchers have developed a new AI training dataset, the Harvard OpenAI-Microsoft Dataset, aimed at…

5 days ago

Apple Finalizes its AI Toolset With iOS 18.2

Apple's iOS 18.2 Update Introduces Powerful AI Features, Including Genmoji and Image Playground Apple’s latest…

6 days ago