Create Your Own MVC Framework

Create Your Own MVC Framework

The Model-View-Controller (MVC) pattern is a widely used software architecture for web applications. It divides the application into three components and defines relationships between them:

  • Model represents database logic ??it is used to communicate with the database
  • Controller represents application logic ??PHP code
  • View represents presentation logic ??HTML code

This way of organizing the application separates the design, programming and the data, allowing the programmers to reuse more code and be more productive. Also, it improves collaboration on projects where designers and programmers are working together.

For most of projects, you would use an already built PHP MVC framework. However, it is good to learn how to create your own MVC framework in order to have a better understanding of how the framework core works. It will also prepare you for large projects where creating a custom framework is more efficient than using an existing one.

Directory Structure

We will use the following directory structure in this tutorial:

  • application ??contains application-specific files
    • controllers ??all controllers go here
    • models ??all models go here
    • views ??all views are stored here
  • config ??contains configuration files
  • core ??core classes will be stored here
  • css ??folder for CSS stylesheets
  • images ??folder for images
  • js ??folder for JavaScript files

Note that all folder names are lower case. Each folder has an index.html file to prevent directory index access:

	403 Forbidden

Directory access is forbidden.

URL Rewriting

MVC Frameworks route all URL requests to one file ??index.php. We will do the same by creating an .htaccess file:

RewriteEngine onRewriteBase /RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteCond $1 !^(images|photos|css|js|robots.txt)RewriteRule ^(.*)$ /index.php?url=$1 [L] 

So, all HTTP requests (except image, photos, css and js folders and robots.txt) are now handled by index.php. Index.php configures the correct file paths and runs the bootstrap.php file:

Autoloading PHP Classes

One of the most important features of any framework is class autoloading. It enables you to just create a file with a new class (e.g. a controller or a model) and it becomes instantly available for use in the application. Autoloading is handled by bootstrap.php file:

In this example, all classes inside core, controllers and models folders are automatically loaded. Naming conventions must be followed here: controller filename is always the lowercase class name, while the model filename is the same as the class name.

Bootstrap.php also loads the configuration file (config.php) and the file with helper functions (functions.php). At last, it sends the URL to the router class.

Configuration

The configuration file contains the database credential and other information that is available throughout the entire application:

Routing

All routes in the framework are in the following format: controller_name/method_name. For example, if you open the web page http://www.example.com/home/welcome, the framework would execute the method named "welcome" located inside the "home" controller. This process is executed by router.php inside the core folder:

Before explaining a sample controller class, let's see the two classes which are needed for any controller. The classes are Application and Controller. Application is the class that executes important processes before the controller is created. In this case, it sets proper error reporting values, unregisters globals and escapes all input (GET, POST and COOKIE variables):

set_reporting();		$this->remove_magic_quotes();		$this->unregister_globals();	}		private function set_reporting() {		if (DEVELOPMENT_ENVIRONMENT == true) {	    error_reporting(E_ALL);	    ini_set('display_errors','On');		} else {		    error_reporting(E_ALL);		    ini_set('display_errors','Off');		    ini_set('log_errors', 'On');		    ini_set('error_log', ROOT.DS.'tmp'.DS.'logs'.DS.'error.log');		}	}		private function strip_slashes_deep($value) {    	$value = is_array($value) ? array_map(array($this,'strip_slashes_deep'), $value) : stripslashes($value);    	return $value;	}		private function remove_magic_quotes() {		if ( get_magic_quotes_gpc() ) {		    $_GET    = $this->strip_slashes_deep($_GET);		    $_POST   = $this->strip_slashes_deep($_POST);		    $_COOKIE = $this->strip_slashes_deep($_COOKIE);		}	}		private function unregister_globals() {	    if (ini_get('register_globals')) {	        $array = array('_SESSION', '_POST', '_GET', '_COOKIE', '_REQUEST', '_SERVER', '_ENV', '_FILES');	        foreach ($array as $value) {	            foreach ($GLOBALS[$value] as $key => $var) {	                if ($var === $GLOBALS[$key]) {	                    unset($GLOBALS[$key]);	                }	            }	        }	    }	}}

The Controller class is a generic controller class that inherits the Application class and contains important functions for communicating with models and views:

controller = $controller;       		 $this->action = $action;		$this->view = new View();	}		// Load model class	protected function load_model($model) {		if(class_exists($model)) {			$this->models[$model] = new $model();		}			}		// Get the instance of the loaded model class	protected function get_model($model) {		if(is_object($this->models[$model])) {			return $this->models[$model];		} else {			return false;		}	}		// Return view object	protected function get_view() {		return $this->view;	}}

There are also generic classes for models and views:

db = new MysqliDb(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);	}	}

Since models only communicate with the database, the role of this class is to load the database class and make it available inside all models. The database class file is named sql.php and the class itself can be downloaded from here.

View class contains functions required for using PHP variables inside views and for rendering HTML code:

variables[$name] = $value;    }         function render($view_name) {        extract($this->variables);				if( file_exists(ROOT . DS . 'application' . DS . 'views' . DS . $view_name . '.php') ) {			include (ROOT . DS . 'application' . DS . 'views' . DS . $view_name . '.php');		} else {			/* throw exception */								}    } }

Creating Your First Model, View and Controller

Let's create the first controller in this tutorial and call its class "Item." So, the filename will be item.php and it will be stored in application/controllers folder:

load_model('CategoryModel');		$this->load_model('ItemModel');	}		public function index() {		// Load search page		$this->search();	}		public function search()  {		// Call a model function		$items = $this->get_model('ItemModel')->getAll();						// Set view variables$this->get_view()->set('items', $items);// Render view		$this->get_view()->render('item/item_list_view');	}}

Each controller must inherit the core Controller class. The models are loaded for use inside a controller using the load_model function. Multiple models can be used in a controller.

The Index function is triggered when the following URL is requested: http://www.example.com/item/ (no 2nd parameter). In this case, we will just load the search function.

Models are created in application/models folder. The ItemModel class filename will be ItemModel.php:

db->get('item');	}	}

After creating a model and a controller, let's create a view named item_list_view.php:

render('common/meta'); 	$this->render('common/header');	?>
id; ?> name; ?>
render('common/footer');?>

Views are store inside application/views folder. Note that other views can be rendered inside the main view, which allows you to have partial views, such as header and footer.

Conclusion

We have just created a basic MVC framework. You can now see the theory from the first paragraph in practice ??controller does all the programming and calls the required models and views, models execute the database operations, and views only show HTML code (with the required PHP variables inserted).

devx-admin

devx-admin

Share the Post:
Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023,

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed

Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at the Lubiatowo-Kopalino site in Pomerania.

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will result in job losses. However,

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023, more than one-fifth of automobiles

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed are at the forefront because

Sunsets' Technique

Inside the Climate Battle: Make Sunsets’ Technique

On February 12, 2023, Luke Iseman and Andrew Song from the solar geoengineering firm Make Sunsets showcased their technique for injecting sulfur dioxide (SO₂) into the stratosphere as a means

AI Adherence Prediction

AI Algorithm Predicts Treatment Adherence

Swoop, a prominent consumer health data company, has unveiled a cutting-edge algorithm capable of predicting adherence to treatment in people with Multiple Sclerosis (MS) and other health conditions. Utilizing artificial

Personalized UX

Here’s Why You Need to Use JavaScript and Cookies

In today’s increasingly digital world, websites often rely on JavaScript and cookies to provide users with a more seamless and personalized browsing experience. These key components allow websites to display

Geoengineering Methods

Scientists Dimming the Sun: It’s a Good Thing

Scientists at the University of Bern have been exploring geoengineering methods that could potentially slow down the melting of the West Antarctic ice sheet by reducing sunlight exposure. Among these

why startups succeed

The Top Reasons Why Startups Succeed

Everyone hears the stories. Apple was started in a garage. Musk slept in a rented office space while he was creating PayPal with his brother. Facebook was coded by a

Bold Evolution

Intel’s Bold Comeback

Intel, a leading figure in the semiconductor industry, has underperformed in the stock market over the past five years, with shares dropping by 4% as opposed to the 176% return

Semiconductor market

Semiconductor Slump: Rebound on the Horizon

In recent years, the semiconductor sector has faced a slump due to decreasing PC and smartphone sales, especially in 2022 and 2023. Nonetheless, as 2024 approaches, the industry seems to

Elevated Content Deals

Elevate Your Content Creation with Amazing Deals

The latest Tech Deals cater to creators of different levels and budgets, featuring a variety of computer accessories and tools designed specifically for content creation. Enhance your technological setup with

Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security. These carefully designed learning courses

Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers to better manage smaller unmanned

Tech Partnership

US and Vietnam: The Next Tech Leaders?

The US and Vietnam have entered into a series of multi-billion-dollar business deals, marking a significant leap forward in their cooperation in vital sectors like artificial intelligence (AI), semiconductors, and

Huge Savings

Score Massive Savings on Portable Gaming

This week in tech bargains, a well-known firm has considerably reduced the price of its portable gaming device, cutting costs by as much as 20 percent, which matches the lowest

Cloudfare Protection

Unbreakable: Cloudflare One Data Protection Suite

Recently, Cloudflare introduced its One Data Protection Suite, an extensive collection of sophisticated security tools designed to protect data in various environments, including web, private, and SaaS applications. The suite

Drone Revolution

Cool Drone Tech Unveiled at London Event

At the DSEI defense event in London, Israeli defense firms exhibited cutting-edge drone technology featuring vertical-takeoff-and-landing (VTOL) abilities while launching two innovative systems that have already been acquired by clients.

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications, it suffers from certain limitations.

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure. The company has decided to

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones beyond the visual line of

Mortgage Rate Challenges

Prop-Tech Firms Face Mortgage Rate Challenges

The surge in mortgage rates and a subsequent decrease in home buying have presented challenges for prop-tech firms like Divvy Homes, a rent-to-own start-up company. With a previous valuation of

Lighthouse Updates

Microsoft 365 Lighthouse: Powerful Updates

Microsoft has introduced a new update to Microsoft 365 Lighthouse, which includes support for alerts and notifications. This update is designed to give Managed Service Providers (MSPs) increased control and

Website Lock

Mysterious Website Blockage Sparks Concern

Recently, visitors of a well-known resource website encountered a message blocking their access, resulting in disappointment and frustration among its users. While the reason for this limitation remains uncertain, specialists

©2023 Copyright DevX - All Rights Reserved. Registration or use of this site constitutes acceptance of our Terms of Service and Privacy Policy.

Sitemap