Super Simple Roll Your Own MVC Framework in PHP

Super Simple Roll Your Own MVC Framework in PHP
Photo by Mohammad Rahmani / Unsplash

Please note that it is essential for me to emphasize that the code and techniques presented here are intended solely for educational purposes and should never be employed in real-world applications without careful consideration and expert guidance to deploy an application using these methods.


The design principles of the Model-View-Controller (MVC) are very important for a PHP Application to be designed for ease of development, working with other developers, and have a standard design that people can pickup and develop to extend functionality even more. As mentioned in the name of it, the web application will be separated into three different yet interconnected components.

First, we have the Model (or the M part of MVC) which represents the web application's data and business logic. This means that it is responsible for retrieving, updating, and storing the data. Next comes the View (or the V of the MVC). The view will act as the presentation layer which is responsible for presenting and styling the data for the frontend of the web application. Finally, comes the Controller (which is the C of the MVC). This acts as the middle layer between the Model and View. It will handle user input then determine which model(s) – there can be more than one – to use then decide which view to present to the end user.

Based on this logic, the model-view-controller design enforces a clear separation of data management. This means it separates the user interface from the application logic. The overall goal of this is to make it so much easier for people to understand, maintain, and extend an application even further.


I recommend that you read our issues with The PHP Community and Development Sucks article a try. It covers a lot of the issues I have had with the PHP programming language for quite a few years.
The PHP Community and Development Sucks
The issues which I have had with the PHP for the last ten years is the community, tutorials and/or guides, and the development of web applications. Yet at the same time, the core of PHP is the amazing people which I have met so far with talent – they have

The Application Prerequisites

In the following guide, you will learn how to design a very simple PHP Framework from scratch. For this guide to work in your favor, you should have at least a basic understanding of the following tools and programming logic.

  • Object-Oriented Programming (OOP) Concepts
  • Composer
  • HTML/CSS

Creating a New Project

The first step is to create a new directory. This is for all of the project files which we will create and maintain to reside in. Then you are going to open the project folder in the Integrated Development Environment (IDE) of your choice. I highly recommend people to try out and use Visual Studio Code (VSCode). Once you open the project directory in the IDE, you are going to run the following command in the terminal.

composer init

You can easily leave all of the questions that the init process is going to ask completely blank. You do not need to fill out this information. When you are asked to add dependencies – that also includes the dev dependencies – you are going to type no then press enter – for now.

Once this is completed, you will see something alone these lines right below.

“PSR-4 autoloading configured. 
Use “namespace CoderOasis\MVC;” in src/”

The Directory Structure

The most common directory structure which web applications using the MVC Design is shown right below. You can technically change this around to your liking, but this base structure provided usually works the best for convivence.

public/ # this is where the domain is pointed
src/
   Controllers/
   Models/
   Routes/
   Views/
vendor/ # automatically created by composer

Route Handler

The Router is one of the most important files in this MVC design. I am going to create a Router.php file inside src/ directory. This will map the routes to the correct controller.

<?php

namespace MVC;

class Router
{
    protected $routes = [];

    private function addRoute($route, $controller, $action, $method)
    {

        $this->routes[$method][$route] = ['controller' => $controller, 'action' => $action];
    }

    public function get($route, $controller, $action)
    {
        $this->addRoute($route, $controller, $action, "GET");
    }

    public function post($route, $controller, $action)
    {
        $this->addRoute($route, $controller, $action, "POST");
    }

    public function dispatch()
    {
        $uri = strtok($_SERVER['REQUEST_URI'], '?');
        $method =  $_SERVER['REQUEST_METHOD'];

        if (array_key_exists($uri, $this->routes[$method])) {
            $controller = $this->routes[$method][$uri]['controller'];
            $action = $this->routes[$method][$uri]['action'];

            $controller = new $controller();
            $controller->$action();
        } else {
            throw new \Exception("No route found for URI: $uri");
        }
    }
}

Now, I am going to set the initial route. The next step is to create a index.php file inside src/Routes/ directory. You can map the routes for POST and GET requests here separately – for whichever your web application is going to use and for what major functionality.

<?php

use MVCp\Controllers\HomeController;
use MVC\Router;

$router = new Router();
$router->get('/', HomeController::class, 'index');
$router->dispatch();

Controller Handler

First, I am going to create a Controller.php inside the src/ folder. It is going to be something alone the lines of the following code example.

<?php

namespace MVC;

class Controller
{
    protected function render($view, $data = [])
    {
        extract($data);
        include "Views/$view.php";
    }
}

For this next part, I am going to add a HomeController to handle the request. Inside the src/Controllers/ directory. Then I am going to create the HomeController.php file with an index method to handle the homepage of the web application.

<?php

namespace App\Controllers;
use App\Controller;

class HomeController extends Controller
{
    public function index()
    {
        $this->render('index');
    }
}

Model Handler

For the model handler, I a file Journals.php inside the Models/ directory. This will represent the Journals in the web application.

<?php

namespace MVC\Models;

class Journal
{
    public $name;
    public $publishedYear;

    public function __construct($name, $publishedYear)
    {
        $this->name = $name;
        $this->publishedYear = $publishedYear;
    }
}

For this example, let’s add some Journals to the homepage of the we application. I am going to update the HomeController.php to load some Journals.

<?php

namespace MVC\Controllers;
use MVC\Controller;
use MVC\Models\Journal;

class HomeController extends Controller
{
    public function index()
    {
        $journals = [
            new Journal('My Third Journal Entry', '2023'),
            new Journal('My Second Journal Entry', '2022'),
            new Journal('My First Journal Entry', '2021')
        ];
        
        $this->render('index', ['journals' => $journals]);
    }
}

Finally, I will update the index.php inside the Views/ folder.

<h1>Welcome to Simple PHP MVC Starter!</h1>

<ul>
    <?php foreach ($journals as $journal) : ?>
        <li><?= $journal->name ?> (<?= $journal->publishedYear ?>)</li>
    <?php endforeach; ?>
</ul>

Running the Web Application

If I managed to code everything correctly – I promise I even tested the code before I published the article, the application is now ready to serve the homepage to the public. Navigate to the public folder and run the built-in PHP web server to test it.

cd mvc
php -S localhost:9999

Even though this is an extremely simple start to creating a PHP Framework from scratch is a massive undertaking. I strongly do not recommend doing this by yourself. Overall, it’s a big project that can take a considerable amount of time and effort. This is more of a learning exercise than actually using it in production.


Do you like what you're reading from the CoderOasis Technology Blog? We recommend reading our Understanding Heap Memory in Java Applications as the next article.
Understanding Heap Memory in Java Applications
Let us begin with a pretty simple question. Does every Java Developer understand how memory works in Java? One goal of a Java Developer is to make sure their application has some of the best performance it can get from fine-tuning their Java software applications. Java Memory Management takes some

The CoderOasis Community

Did you know we have a Community Forums and Discord Server? which we invite everyone to join us? Want to discuss this article with other members of our community? Want to join a laid back place to chill and discuss topics like programming, cybersecurity, web development, and Linux? Consider joining us today!
Join the CoderOasis.com Discord Server!
CoderOasis offers technology news articles about programming, security, web development, Linux, systems admin, and more. | 112 members
CoderOasis Forums
CoderOasis Community Forums where our members can have a place to discuss technology together and share resources with each other.