Analysis of php mvc implementation principles (a simple MVC framework example) _ PHP Tutorial

Source: Internet
Author: User
Analysis of the implementation principle of php mvc mode (a simple MVC framework example ). Their working principles should also be of interest to everyone. next I will talk about what a mvc framework looks like. Routing mechanisms are provided through URLs on the internet. Therefore, different URLs have their working principles and you should be interested in them. next I will talk about what a mvc framework looks like.

Routing mechanism

We provide services through URLs on the Internet, so different URLs have different services. Users access different pages to obtain different services. Then how does our service distinguish different services through URLs.

Our web programs need to find different files through URLs for different business logic processing. Our routing mechanism is to find the corresponding controller and action based on the url, and then perform specific business logic processing by action.

A simple controller

The code is as follows:


// Define a controller
Class UserControler extends Controller {
// Define an action method. Note that it must be public.
Public function index (){
// Do business code
}
}

The corresponding rules are mapped to different frameworks. The following is the URL routing of the CodeIgniter framework. it tries its best to analyze the URL situation.

File path/system/core/URI. php

The code is as follows:


// Check whether the command line is running
If (php_sapi_name () = 'cli 'or defined ('stdin ')){
$ This-> _ set_uri_string ($ this-> _ parse_cli_args ());
Return;
}

// First try REQUEST_URI to adapt to most situations
If ($ uri = $ this-> _ detect_uri ()){
$ This-> _ set_uri_string ($ uri );
Return;
}

// Check whether 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. Check out 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;
}

// Give up the route
$ This-> uri_string = '';
Return;

Through 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 loads to the controller and calls the action.

The following code is available in/system/core/Codeigniter. php. Before that, Codeigniter will assign values based on the values in $ _ SERVER ['path _ INFO] (this is all set by itself, by default, CI will have many if branches for judgment ).

The code is as follows:


// Approximately 250 rows
Include (APPPATH. 'controllers/'. $ RTR-> fetch_directory (). $ RTR-> fetch_class ().'. php ');

$ Class = $ RTR-> fetch_class ();
$ Method = $ RTR-> fetch_method ();

// Approximately 308 rows
$ CI = new $ class ();

// Approximately 359 rows
Call_user_func_array (array (& $ CI, $ method), array_slice ($ URI-> rsegments, 2 ));

In this way, our controller and its method are called through this, and the next step is to write your own business logic code.


View display

After our business logic code is written, we need to display the page. Many common MVC frameworks write such calls on pages.

The code is as follows:

// Action method 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 );
}


Write the code in the view file view/path/file.html.

The code is as follows:


Name:
Age:


This section describes how to render data to a view. I have been curious about this code before. now I understand how to implement it.

The code is as follows:

Protected function render ($ template, array $ var = array ())
{
Extract ($ var); // extracts variables from the array.
Ob_end_clean (); // close the output buffer content at the top layer.
Ob_start (); // start a new buffer
Require TEMPLATE_ROOT. $ template. '.html '; // Load view
$ Content = ob_get_contents (); // Obtain the buffer content
Ob_end_clean (); // disable the buffer.

// Ob_end_flush (); // This is the content of the buffer zone that is directly output. you do not need to cache it again.
Ob_start (); // start a new buffer zone for subsequent programs
Return $ content; // return the text, which can also be echo in bytes and end the code.
}

In this short few lines of code, all are the essence. these are very important. they are all built-in php functions. Next, let's analyze them in detail.

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

The second ob_end_clean () function is to close the top-layer buffer, so that some text accidentally echo from the previous program can be clearly understood and a buffer can be re-opened for the next row.

The third ob_start () is to enable a new buffer to place the view content in the buffer zone. Of course, the buffer has a certain size. if the content exceeds the set value of the buffer, it will be automatically sent to the server.

The fourth require file. this is the first parameter. you can load the View file according to your own rules. The file can contain php and html code. Any local variables declared by the render () function or any global variables that can be accessed here can be accessed in the require file.

The fifth $ content = ob_get_contents () is important to retrieve the content of the buffer but not clear it.

The seventh ob_start () is to re-enable a buffer, so that the following program needs to use a buffer. Some write frameworks may not need to perform operations on the $ content, so the ob_end_flush () will output the buffer content directly.

This is a simple process of displaying views. If you directly use this method, it is inconvenient to modularize the view, so some frameworks won't be used directly.

From this function, we can also see that the program is a bit similar to the program interruption protection field. However, the interruption protection site stores the data first, and then restores the data when it returns. Here, only the previous buffer is closed, a new buffer is enabled, and the buffer is disabled. in the past, another buffer is enabled.

So far, we can see a simple php mvc framework. If you are interested, you can develop an MVC framework or a more in-depth HMVC.

Bytes. The routing mechanism is provided through URLs on the Internet, so different URLs are...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.