Creating a Simple MVC Framework in PHP Tutorial

Introduction

In this tutorial, I will teach you how to Create a Simple MVC Framework in PHP. The tutorial aims to provide you guys with a reference or guide to widen your knowledge and enhance your PHP programming capabilities by understanding and creating a simple MVC Framework. This is useful for you especially if you are planning to create wide broad scope of web applications. This will help you to learn to create your own MVC Framework for your own development and projects.

What is MVC Framework?

MVC stands for Model-View-Controller (MVC). This framework is an architecture composed of three (3) logical components which are the Model, View, and Controller. Each architectural element is designed to manage particular application development aspects. It separates the presentation layer from the business logic layer. Initially, it was applied to desktop graphical user interfaces (GUIs). The most widely used industry standard web development framework for building scalable and flexible projects today is MVC. Mobile application design is another usage for it.

Let's Get Started

Now, before we start building our simple MVC Framework, make sure that the following requirements are already installed on your local machine.

  • XAMPP/WAMPP or any equivalent software to run our PHP Scripts.
  • Code Editor such as Notepad++, Submile Text, VS Code, etc.
  • Make sure that your Apache/Nginx or any equivalent service is already started and running.

Next, create a new directory for your source codes for this MVC Framework. For XAMPP, place this folder inside the XAMPP's htdocs directory. If you are using WAMP, place it www directory.

Creating the .htaccess

Let us create our .htaccess file first. Here, we will configure our app routing and rewrite some conditions and rules. Save this file as .htaccess.

  1. <IfModule mod_rewrite.c>
  2.  
  3. Header set Access-Control-Allow-Origin "*"
  4. RewriteEngine on
  5.  
  6. RewriteCond %{REQUEST_FILENAME} !-f
  7. RewriteCond %{REQUEST_FILENAME} !-d
  8. RewriteCond %{REQUEST_FILENAME} !-l
  9.  
  10. RewriteRule ^([0-9a-zA-Z].+)$ index.php?main_route=$1 [NC,QSA,L]
  11.  
  12.  
  13. </IfModule>

Creating the Main Classes

The following snippets are the file scripts that hold our main classes for the framework. These PHP Files will be loaded on the index page of the application. Create a new directory inside your source code folder named inc and store the following files scripts in the created directory.

routes.php

This file contains the PHP Class Script that manages our framework page routing and parameters.

  1. <?php
  2.  
  3. class Routes {
  4.  
  5. public function __construct($parameters){
  6. $params = explode("/", trim($parameters, "/"),3);
  7.  
  8. $controller = isset($params[0]) && !empty($params[0]) ? $params[0] : 'DefaultController';
  9. $instance = isset($params[1]) && !empty($params[1]) ? $params[1] : 'index';
  10. $args = isset($params[2]) ? explode("/", trim($params[2], "/")) : [];
  11.  
  12.  
  13. $controller = ucwords($controller);
  14. require_once "controllers/{$controller}.php";
  15. if(class_exists($controller)){
  16. $controller_class = new $controller();
  17. if(method_exists($controller_class, $instance)){
  18. $controller_class->$instance($args);
  19. }else{
  20. die("Undefined {$instance} Method in {$controller} Controller");
  21. }
  22. }else{
  23. die("Undefined {$controller} Controller");
  24. }
  25. }
  26. }

controller.php

This PHP Class contains the main methods and objects for our Controllers.

  1. <?php
  2. class Controller {
  3.  
  4. protected $render;
  5.  
  6. public function __construct(){
  7. $this->render = new Render();
  8. }
  9. public function load_model($model){
  10. $model_main = new Model();
  11. return $model_main->load_model($model);
  12. }
  13. }

render.php

This PHP Class handles our views or the pages' template files.

  1. <?php
  2.  
  3. class Render {
  4. public function view($view_filename, $data = []){
  5. $data = (object) $data;
  6. include_once("views/{$view_filename}.php");
  7. }
  8. }

model.php

This PHP Class handles the scripts for loading our Models.

  1. <?php
  2.  
  3. class Model {
  4. public function load_model($model){
  5. $model = ucwords($model);
  6. if(is_file("models/{$model}.php")){
  7. require_once "models/{$model}.php";
  8. if(class_exists($model)){
  9. return new $model();
  10. }else{
  11. die("Undefined {$model} Model");
  12. }
  13. }
  14. }
  15. }

Creating the Index File

The following snippet is the PHP Script that handles all the classes, methods, and routing of this MVC Framework. Save this file as index.php in your source code folder root directory.

  1. <?php
  2.  
  3. include_once('inc/routes.php');
  4. include_once('inc/controller.php');
  5. include_once('inc/render.php');
  6. include_once('inc/model.php');
  7.  
  8. $route = $_GET['main_route'] ?? "";
  9. new Routes($route);

Creating the Sample Controllers

Here are the following snippets for creating our Default and Sample Controller for this MVC Framework. Create a new directory in your source code folder naming controllers and store the following snippets on this directory.

DefaultController.php

The script below is the default controller of this MVC Framework. This controller will run as default if no controller is stated at the URL or route.

  1. <?php
  2.  
  3. class DefaultController extends Controller {
  4. public function __construct(){
  5. parent::__construct();
  6. }
  7. public function __destruct(){
  8.  
  9. }
  10. public function index(){
  11. $this->render->view('default');
  12. }
  13. }

Home.php

The following controller contains our sample page control for this framework. This controller contains 2 instances which are the index (default) and the load_data method. Here, on the index method, you will see that the controller is passing the parameters or arguments to the PHP file to view. The load_data method is an example instance of the controller that connects with the Model to query data.

  1. <?php
  2.  
  3. class Home extends Controller{
  4.  
  5. public function index($data=[]){
  6. echo $this->render->view('home', $data);
  7. }
  8. public function load_data(){
  9.  
  10. $model = $this->load_model('SampleModel');
  11.  
  12. $data = $model->sample_query();
  13.  
  14. $this->render->view("load_data", ["query_data" => $data]);
  15.  
  16. }
  17.  
  18. }

Creating the Sample Model

The following snippet is the PHP Script for the example model for this framework. The model contains a method that queries simple data and returns the data to the controller.

  1. <?php
  2.  
  3. class SampleModel {
  4. public function sample_query(){
  5. $data = (object) [
  6. [
  7. "id" => 1,
  8. "name" => "John Smith",
  9. "postion" => "Web Developer"
  10. ],
  11. [
  12. "id" => 2,
  13. "name" => "Samantha Lou",
  14. "postion" => "Project Manager"
  15. ],
  16. [
  17. "id" => 1,
  18. "name" => "Mark Cooper",
  19. "postion" => "Senior Programmer"
  20. ]
  21. ];
  22.  
  23. return $data;
  24. }
  25. }
  26.  
  27. ?>

Creating the Views

Here are the following snippets for the interfaces of our simple application using this simple MVC Framework that we created. Same the files using the given file name otherwise you will need to change the rendered view filename at the controller.

default.php

  1. <h1>This is the default page of this simpe MVC Framework in PHP.</h1>
  2. <hr>
  3. <h3>Sample Pages</h3>
  4. <ul>
  5. <li><a href="./home/index/param1/param2">Sample Home Page with Parameters or Arguments</a></li>
  6. <li><a href="./home/load_data/">Sample Page that Queries Data using Model</a></li>
  7. </ul>

home.php

  1. <h1>Sample Home Page</h1>
  2. <hr>
  3. <h3>Sample Arguments or Parameters sent to this controller.</h3>
  4. <pre>
  5. <?php
  6. print_r($data);
  7. ?>
  8. </pre>
  9. <a href="/php_mvc">Back to Default Page</a>

load_data.php

  1. <h1>Sample Page 1</h1>
  2. <hr>
  3. <h3>Sample queried data in model</h3>
  4. <pre>
  5. <?php
  6. print_r($data->query_data);
  7. ?>
  8. </pre>
  9. <a href="/php_mvc">Back to Default Page</a>

There you go! You can now test the sample application using our created simple PHP MVC Framework. Browse localhost/php_mvc on your preferred browser to test the application if it works properly. I have also provided a complete source code zip file I created for this tutorial. You can download it by clicking the Download Button below this article.

That's the end of this tutorial. I hope this PHP MVC Framework Creation Tutorial will help you with what you are looking for and adds up to your knowledge for developing a web application using the PHP Language.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)

Comments

Submitted byAysad Kozanoglu (not verified)on Thu, 12/01/2022 - 00:43

thanks for code example for framework creation. htaccess metodic is very old school type of solution and is not universal. many people uses traefik, nginx, lighthttpd, hayproxy as webserver as go. so try to uvniverse your example code without htaccess rules.

Add new comment