Home > Backend Development > PHP Tutorial > Analysis of PHP's MVC pattern implementation principle (a simple MVC framework example)_PHP tutorial

Analysis of PHP's MVC pattern implementation principle (a simple MVC framework example)_PHP tutorial

WBOY
Release: 2016-07-13 10:31:37
Original
823 people have browsed it

You may also be interested in their working principles. Let me talk about what an MVC framework looks like.

Routing mechanism

On the Internet, we all provide services through URLs, so different URLs have different services. Users access different pages and receive different services. So how does our service distinguish different services through URLs.

Our web program must find different files through URLs and perform different business logic processing. Our routing mechanism is to find the corresponding controller and action based on the URL, and then the action performs specific business logic processing.

A simple controller

Copy code The code is as follows:

//Define a controller
class UserControler extends Controller{
// Define an action method, please note that it must be public
public function index(){
// do business code
}
}

The specific corresponding rules are mapped differently by different frameworks. The following is the URL routing of the CodeIgniter framework. It will try its best to try various possibilities to analyze the URL situation.

File path/system/core/URI.php

Copy the code The code is as follows:

// Check if it is run from the command line
if (php_sapi_name( ) == 'cli' or defined('STDIN')){
$this->_set_uri_string($this->_parse_cli_args());
return;
}

// First try REQUEST_URI which adapts to most situations
if ($uri = $this->_detect_uri()){
$this->_set_uri_string($uri);
return;
}

// Check if the PATH_INFO variable exists? nginx needs to be configured
// Note: some servers seem to have trouble with getenv() so we'll test it two ways
$path = (isset($_SERVER['PATH_INFO'])) ? $_SERVER[ 'PATH_INFO'] : @getenv('PATH_INFO');
if (trim($path, '/') != '' && $path != "/".SELF){
$this-> ;_set_uri_string($path);
return;
}

// There is no PATH_INFO, look at QUERY_STRING?
$path = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : @getenv('QUERY_STRING');
if (trim($path, '/') != ''){
$this->_set_uri_string($path);
return;
}

//Try to get information from $_GET
if (is_array($_GET) && count($_GET) == 1 && trim(key($_GET) ), '/') != ''){
$this->_set_uri_string(key($_GET));
return;
}

// Try your best, give up Route
$this->uri_string = '';
return;

After the above attempt, the next step is how to use the routing mechanism to load the correct controller.

Controller loading mechanism

Let’s take a look at how the Codeigniter framework is loaded into the controller and calls actions.

There is the following code in /system/core/Codeigniter.php. Codeigniter will assign values ​​based on the value in $_SERVER['PATH_INFO] before this (this all depends on its own settings. By default, CI will have many if branches for judgment).

Copy code The code is as follows:

//About line 250
include(APPPATH.'controllers/'. $RTR->fetch_directory().$RTR->fetch_class().'.php');

$class = $RTR->fetch_class();
$method = $RTR ->fetch_method();

//About line 308
$CI = new $class();

//About line 359
call_user_func_array(array( &$CI, $method), array_slice($URI->rsegments, 2));

That’s it, our controller and its methods are called through this. The next step is to write your own business logic code.


View view display

After our business logic code is written, we need to display the page. The page calls of many common MVC frameworks are written like this.

Copy code The code is as follows:
//Method of action in controller
public function index(){
// ... A lot of business logic code
$data = array('name'=>'abc', 'age'=>12, .... );
return $this->render ('view/path/file.html',$data);
}

Then write some code in the view file view/path/file.html.
Copy code The code is as follows:

Name:
Age:

How does this code render data into the view? I have always been curious about this code before, but now I understand it. Let’s see how it is implemented.
Copy code The code is as follows:
protected function render($template, array $var = array() )
{
extract($var); // Extract variables from the array
ob_end_clean (); // Close the top-level output buffer content
ob_start (); // Start a new buffer
require TEMPLATE_ROOT . $template . '.html'; //Load the view
$content = ob_get_contents (); // Get the contents of the buffer
ob_end_clean (); // Close the buffer

/ /ob_end_flush(); // This is to directly output the contents of the buffer without caching it again.
ob_start(); //Start a new buffer and use it for subsequent programs.
return $content; //Return the text. You can also echo the bytes here and end the code.
}

In these few lines of code, they are all the essence. These are very important, all of them are built-in functions of PHP. Next, let’s analyze them in detail.

Look at the first extract($var). This function imports variables from an array into the current symbol table. Just now, we extracted the name and age from the $data array, so that we can use $name $age in the view. For more details, please refer to http://www.php.net/manual/zh/function.extract.php

The function of the second ob_end_clean() is to close the top-level buffer, in order to clear some text that was accidentally echoed by the previous program, and to reopen a buffer for the next line.

The third ob_start() is to open a new buffer in order to put the content of the view into the buffer. Of course, the buffer has a certain size. If the content exceeds the buffer's set value, it will be automatically sent to the server.

The fourth require file, this is the first parameter, loads the view file according to its own rules. The files can contain php and html codes. Any local variables you declare in this render() function or any global variables accessible here can be accessed in the require file.

The fifth $content = ob_get_contents () is very important, it is to take out the contents of the buffer but not clear it.

The seventh ob_start() is to reopen a buffer, in order to use the buffer for the following program. If the writing framework may not need to operate on the contents of $content, then ob_end_flush() can directly output the contents of the buffer.

This is a very simple process of displaying views. If you use this directly, it is not convenient to modularize the view, so some frameworks will not use it so directly.

We can also see from this function that the program is somewhat similar to the program interrupt protection scene. It's just that the interruption protection site will save the data first, and then restore it when returning. Here we only have to close the previous buffer, open a new buffer, close this buffer, and open another buffer.

So far, we have seen a simple PHP MVC framework. If you are interested, you can develop an MVC framework yourself, or a more in-depth HMVC.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/762612.htmlTechArticleYou may also be interested in their working principles. Let me talk about what an MVC framework looks like. Routing mechanism On the Internet, we all provide services through URLs, so different URLs are...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template