HOW TO IMPLEMENT THE MVC MODEL WITH PHP

Problem statement

The MVC model is the most widely used model in web application development; it's a software architecture model created to manage and build software projects more systematically.

Currently, there are quite a few PHP frameworks, and they are all built on the MVC model, which shows just how important it is.

MVC model

Components in the MVC model

This model consists of three main components, each playing a different role.

  • ModelIts function is to manipulate the database, meaning it contains all the functions and methods for directly querying the data. The controller will use these functions and methods to retrieve the data and send it to the View.
  • ViewIts function is to receive data from the controller and display the content in HTML code; you can think of it as a user interface component.
  • OfficerIt acts as an intermediary between the Model and the View. Its task is to receive requests from the client, then process the request, load the corresponding model, send data to the corresponding view, and return the results to the client.

MVC Pattern cần có trong mọi framework PHP - All Laravel

Processing flow in the MVC model

Step 1Based on the user's request, the controller will call a function (action) and retrieve data if needed through the model.

Step 2After receiving the data, the controller will send it to the View. The View's task is to process the data and convert it into HTML code.

Step 3After the view finishes, the controller will send the view's HTML content back to the client.

Organizing a PHP website using the MVC model.

/var/folders/9g/dcg175n97b950p4vr8s_y2rh0000gn/T/com.microsoft.Word/Content.MSO/D7CA65E9.tmp

The website structure is organized as shown below, where index.php is the file that acts as the website's router.

  1. Install router – index.php

In the MVC model, all user requests are routed by the router. Here's a simple way to write a route in PHP for those new to MVC PHP.

With this setup, all links on the page must be in the following format: /mvc-implement/index/php/xxx

<?php

$currentController = 'Home';

$currentMethod = 'index';

$params = [];

// Function to retrieve elements from URL

//for example: domain/mvc-implement/index/product/detail/1

driver getUrl(){

$url = rtrim($_SERVER['REQUEST_URI'], '/');

$url = filter_var($url, FILTER_SANITIZE_URL);

$url = Heavy('/', $url);

return $url;//[domain,mvc-implement,index,product,detail,1]

}

//get URL

$url = getUrl();

unset($url[0]);unset($url[1]);unset($url[2]);

// Check if the controller exists, then update the controller.

if(isset($url[3])){

if(file_exists(ucwords('controllers/'.$url[3]). '.php')){

$currentController = ucwords($url[3]);

unset($url[3]);

}

}

// Pass the request to the controller

require_once 'controllers/'.$currentController . '.php';

//select method to execute the request

if(isset($url[4])){

$currentMethod = $url[4];

unset($url[4]);

}

// Get the parameter list for the method

$params = $url ? array_values($url) : [];

// Calling a function with parameters is a parameter array

call_user_func_array($currentMethod, $params);

For example, when a request is received.

http://127.0.0.1/mvc-implement/index.php

The server executes the route as follows:

  • Get the array $url using the getUrl() function at line 14, and the result is the array:

[domain,mvc-implement,index.php]

  • Since the array has a maximum index of 2, the remaining rows are not executed.
  • The last line, line 33, is the index function located in the Home controller.

http://127.0.0.1/mvc-implement/index.php/piece

The server executes the route as follows:

  • Get the array $url using the getUrl() function at line 14, and the result is the array:

[domain,mvc-implement,index.php,product]

  • Since the array has a maximum index of 3, line 17 satisfies the condition and updates the controller to handle this request as Product.
  • Since there is no action element, the default action is index.
  • The last line, line 33, is the index function located in the Product controller.
  1. Officer

The remaining task is to build the corresponding controllers for the website with actions to respond to requests redirected by the router.

The following is the Product controller, with the index function returning views of all products, and the detail function returning a view displaying detailed product information by product code.

<?php

require_once 'models/Product.php';

driver index()

{

// Get data from model

$products=getAll();

require_once 'views/products/product.php';

}

driver empire($id)

{

// Get the desired product -> Get the product by code

$product = getProductgByID($id);

require_once 'views/products/productDetail.php';

}

In the example above, you should add a Product model containing methods like getAll() to retrieve all products in the database and getProductByID($id) to get the details of a single product.

  1. View

The remaining task is to design the view that displays the results and return it to the user.

http://127.0.0.1/mvc-implement/index.php/product

http://127.0.0.1/mvc-implement/index.php/product/detail/5

So, we can now organize a website using the MVC model. There are many different ways to organize it; this article only presents a simple method for those new to MVC PHP.

Hopefully, this article provides students with a reference on how to implement a PHP website using the MVC model.

Author: Thy Dao Quoc - Date written: March 22, 2023

Category: Training program, IT - Website Design, IT - Software Applications, Information Technology - Software Applications, TECHNOLOGY AND ENGINEERING SECTOR

0 thoughts on “CÁCH HIỆN THỰC MÔ HÌNH MVC VỚI PHP”

Leave a Reply

Your email address will not be published. Các trường bắt buộc được đánh dấu *