PHP's MVC pattern Implementation Principle analysis (a simple example of MVC framework) _php Tutorial

Source: Internet
Author: User
Tags codeigniter
The principle of their work should also be more interesting, let me tell you what an MVC framework looks like.

Routing mechanism

In the Internet we are all through the URL to provide services, so different URLs have different services. Users access different pages and get different services. So how does our service differentiate between different services through URLs?

Our web application will look for different files through the URL, and do different business logic processing. Our routing mechanism is to find the corresponding controller, and action, based on the URL, and then handle the specific business logic by the action.

A simple controller.

Copy the Code code 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 specific corresponding rules are different for different frame mappings. The following is the URL route for the CodeIgniter framework, which tries to try out various possibilities to analyze the URL situation.

File path/system/core/uri.php

Copy CodeThe code is as follows:
See if it's running 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 this to fit most of the situation
if ($uri = $this->_detect_uri ()) {
$this->_set_uri_string ($uri);
Return
}

See if the PATH_INFO variable exists? Nginx needs to be configured
Note:some servers seem to having trouble with getenv () so we'll test it for it with a ways
$path = (isset ($_server[' path_info '))? $_server[' path_info ': @getenv (' path_info ');
if (Trim ($path, '/')! = ' && $path! = "/". Self) {
$this->_set_uri_string ($path);
Return
}

No path_info, see 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
}

Tried, gave up the route
$this->uri_string = ";
Return

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

Controller loading mechanism

Let's take a look at how the CodeIgniter framework loads into the controller and invokes the action.

The following code is in the/system/core/codeigniter.php. CodeIgniter before this will be based on the value of $_server[' path_info] VALUES (this is set by their own, the default CI he will have a lot of if branch to judge).
Copy the Code code as follows:
It's about 250 lines.
Include (APPPATH. ' controllers/'. $RTR->fetch_directory (). $RTR->fetch_class (). php ');

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

It's about 308 lines.
$CI = new $class ();

It's about 359 lines.
Call_user_func_array (Array (& $CI, $method), Array_slice ($URI->rsegments, 2));

In this way, we call our controller and its methods through this, and then we write our own business logic code.


Display of view views

When our business logic code is finished, we need to show the page. Many of the common MVC frameworks are written on page calls.
Copy CodeThe 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 the code in the view file view/path/file.html.
Copy CodeThe code is as follows:
Name:
Age:

This section of how to render data into a view, which I've been curious about before, now I see, let's see how it's done.
Copy CodeThe code is as follows: Protected function render ($template, array $var = Array ())
{
Extract ($var); Extracting variables from an array
Ob_end_clean (); Close the output buffer contents of the top layer
Ob_start (); Start a new buffer
Require Template_root. $template. '. html '; Load views View
$content = Ob_get_contents (); Get the contents of the buffer
Ob_end_clean (); Close buffer

Ob_end_flush (); This is the content of the direct output buffer, not to be cached again.
Ob_start (); Start a new buffer, give the following program a
return $content; Returns the text, where you can also echo the byte and end the code.
}

In this short line of code, all is the essence, is these very important, all is PHP's built-in function, next we will analyze and analyze concretely.

Take a look at the first extract ($var). This function imports variables from the array into the current symbol table. Just extract the name and age from the $data array so that you can use the $name $age in view views. Please refer to http://www.php.net/manual/zh/function.extract.php for more details.

The second Ob_end_clean () function is to close the top buffer, in order to be the previous program accidentally echo out some of the text given clear, for the next line of re-open a buffer.

The third Ob_start () is to open a new buffer, in order to put the contents of the view into a buffer. Of course, the buffer has a certain size, and if the content exceeds the set value of the buffer, it is automatically sent to the server.

The fourth require file, which is the first parameter, loads the view's files according to its own rules. Where the file can be mixed with PHP, HTML code. Any local variables you declare in this render () function, or any global variables that can be accessed here, can be accessed in require file files.

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

The seventh Ob_start () is to re-open a buffer, in order for the following program to use the buffer. A write frame may not operate on the contents of the $content, so direct ob_end_flush () outputs the contents of the buffer.

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

We can also see from this function that the program is a bit like the program interrupts the sense of protecting the scene. Only the interruption of the protection field will save the data first, and then return to the back of the recovery. Only the last buffer is closed, a new buffer is opened, the buffer is closed, and another buffer is opened.

So far, we have seen a simple PHP MVC framework. If you are interested in developing an MVC framework yourself, or a bit more in-depth hmvc.

http://www.bkjia.com/PHPjc/762612.html www.bkjia.com true http://www.bkjia.com/PHPjc/762612.html techarticle the principle of their work should also be more interesting, let me tell you what an MVC framework looks like. Routing mechanism in the Internet we are all through the URL to provide services, so different URLs have ...

  • Related Article

    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.