Web Development

Building a PHP MVC Framework from Scratch

August 12, 2025 224 views 1 min read

Introduction

In this tutorial, we'll build a simple but powerful PHP MVC framework from the ground up. Understanding how MVC works will make you a better PHP developer.

What is MVC?

MVC stands for Model-View-Controller:

  • Model: Handles data and business logic
  • View: Manages the user interface
  • Controller: Connects Model and View

Project Structure

framework/
├── app/
│   ├── controllers/
│   ├── models/
│   ├── views/
│   └── core/
├── public/
│   ├── index.php
│   └── .htaccess
└── config/
    └── config.php

Step 1: Create the Bootstrap File

Create public/index.php:

Step 2: URL Routing

Create app/core/App.php:

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));
        }
    }
}
?>

Step 3: Base Controller

This provides common functionality to all controllers:

Next Steps

In the next tutorial, we'll add database connectivity and create our first model and controller.

Share this tutorial: