MVC framework, see again

Source: Internet
Author: User
Tags php framework readfile

Objective

This article is written in the original intention, because the group because of a beautiful engineer and caused a commotion, as a woman to see the eyes of the people, how will let go so good to appreciate the chance of beauty [color]. So we will beauty of GitHub to turn out, I was fortunate to see the beautiful writing PHP framework, download down, earnestly to the beauty of learning [worship ing].

The beauty of the framework preface is this:

This framework was originally written because of the discovery of the current popular PHP The framework is bloated and bloated because the framework encapsulates a number of features that I have not used in real-world development, which results in a waste of performance using the framework.

based on this, the The framework was written during the 51 period of the year, and many of the popular frameworks had their own names, and I called them "one ".

At the beginning of the work, because the technical foundation is very bad, so is assigned to do the management platform of the Web page. When I was asked by my colleague what MVC was, I said I didn't know exactly what MVC was. So the colleague describes where to write which part, where is responsible for what function, what part should write in what part. The first time is simply to add a menu to the index.html and jump to a page through this menu.

This framework is simple, but it extracts the core skeleton, although not suitable for the real to build a large site, but suitable for beginners to understand the MVC and the basic construction of the site.

code example

A beautiful simple PHP framework one----https://github.com/linsunny/one

Want to identify beautiful children's shoes, you can play their own imagination online Baidu under.

Code schema

As shown in the framework, the Library folder holds the core class, which is the base class, such as the base class for Model,view,controller, the SQL operation class for MySQL, the start frame logic, and the global core class. index.php as a portal file, the view is stored primarily as views files, such as HTML, or smarty TPL files, St for static files, such as Js,css,image. The model holds a business logic processing code file that handles user requests, saves user data to Db,cache, and accesses Db,cache to read user data. The controller holds the responsibility to receive the user request and calls the model to process the user request and display the user request result in view. The configuration file holds the relevant configuration for various resources (Db,smarty,router, etc.).

Follow-up will show in the code how the documents are responsible for each division .

This section will explore the data flow of this framework by analyzing the entire process of entering a URL in the browser to link to the page display.

After deploying the XMAPP environment on this machine, put the code in the/var/www/html/directory

Url:http://beauty/one-branch/index.php?c=index&a=init

Enter the link as above in the browser, click Enter, you can see the following page.

Attached page display

Data flow

    • Domain name resolution server IP and port

If you enter the URL in the browser: http://beauty/one-branch/index.php?c=index&a=init

    • Find the appropriate code path through the Web server

http resolves the URL above, the domain name beauty resolves to the server 172.16.0.0:80, and then the Apache configuration file on the 172.16.0.0 server (shown below) will find the root path documentroot according to the port. The Http://beauty map to the 172.16.0.0 directory/var/www/html, which will

Http://beauty/one-branch/index.php?c=index&a=init Mapping to Var/www/html/one-branch/index.php?c=index&a=init

The configuration file is as follows:

Attached Apache configuration

The code for index.php is as follows:

<?PHPDefine(' Root_path ',dirname(__file__) .directory_separator);Define(' Controller_path ', Root_path. ' Controller '.directory_separator);Define("View_path", Root_path. " View ".directory_separator);Define("Cache_path", Root_path. " Cache ".directory_separator);Define("Model_path", Root_path. " Model ".directory_separator);Define("Config_path", Root_path. " Config ".directory_separator);Define("Library_path", Root_path. " Library ".directory_separator);Define("St_path", Root_path. " St ".directory_separator);includeConfig_path. "Config.php";includeLibrary_path. "Core.php"; Core:: Run ($config); Main function, entry function

In index.php, in addition to defining some global macro variables, including configuration files and core class files. There is only one sentence to run the code, calling the kernel class core's run function.

Let's see what the main function of the Core::run ($config) function of the framework startup portal is.

    /** * Frame start logic **/     Public Static functionRun$config) {        //Get configuration fileSelf::$_config=$config; //Get Routing information        $router= Self::_parseurl (); //automatic loading of core classesSelf::autoLoad (); //calling the controller and its methodsSelf::initcontroller ($router); }

1. Get the configuration file

Config configuration main configuration:

    • Routing Information for Controller
    • DB and Redis information required in model
    • Information about the template engine in view
<?PHP/** * config.php * * This profile has been loaded in frame loading * * @author linsunny<[email protected]>*//** * Routing configuration information * $config [router][' show '][1] = xx.com/index.php?c=controller&a=action * $config [router][' Show '][2] = xx.com/index.php/controller/action*/$config[' router '] =Array(    ' Default_controller ' = ' index ', ' default_action ' = ' init ', ' show ' + = 2,);/** * Template engine configuration information * $config [' smarty '] [' suffix '] indicates the suffix name of the template file * $config [' smarty '] [' Iscache '] indicates whether the cache (default does not start) * $config [' Smarty ' [' cachelefttime '] indicates the cache validity period (3,600 seconds by default)*/$config[' smarty '] =Array(    ' Template_dir ' = View_path, ' Compile_dir ' and Cache_path. "Compile". Directory_separator, ' cache_dir ' = Cache_path. "Cache". Directory_separator, ' suffix ' and '. htm ', ' iscache ' =true, ' cachelefttime ' = 3600,);/** * Database configuration * $config [' db '] [' conn '] represents the database connection identity; Pconn is a long-term link, the default is instant link*/$config[' db '] =Array(    ' Host ' = ' localhost ', ' user ' = ' root ', ' password ' + ' ', ' dat           Abase ' + ' Idou ', ' table_prefix ' and ' v1_ ', ' charset ' = ' Urf8 ', ' conn ' = = ', ' Port ' = 80                   );

2. parsing URLs to get routing information

Parse parameters to find the appropriate controller class and the running function of the class, as well as the function parameters

Run this script var/www/html/one-branch/index.php, and then parse the back? C=index&a=init with the parameters, the first parameter with? Split, followed by & Split.

Gets the parameter c=index,a=init of C.

3. Automatic loading of core classes

Load the core classes (MODEL,VIEW,CONTROLLER,MYSQL) in the core folder before the code path is require or include.

4. Calling the controller and its methods

C identifies the controller, so this class is the Indexcontroller,c=index,a=init description found in the Controller module Indexcontroller class, and run the Indexcontroller of the class:: init function.

    /** * Initialize controller * Call corresponding Controller and method * @class Core*/     Public Static functionInitcontroller ($router) {        Static $codeAr=Array();//defines a static variable storage array, similar to a singleton pattern, used here to store control method logic        $key=$router[' C ']. "_" .$router[' A ']; $controller=$router[' C ']. "Controller"; $action=$router[' A ']. "Action"; //Load controller Files        $controller _path= Controller_path.$controller. ". php"; Self:: LoadFile ($controller _path); //Create a controller        $object=New $controller(); if(method_exists($object,$action)){            $codeAr[$key] =$object-$action(); }Else{ Self:: Error ("Controller method does not exist!") "); }        return $codeAr[$key]; }

Next, call the Init function in the corresponding indexcontroller. In the INIT function, first call the model function read and write db to obtain the corresponding data, then assign the corresponding data to view, and finally render the view display.

Attach the Indexcontroller code

/** * Page display * Incoming template file name, return the compiled file path * @access public * @return String*/      Public functionDisplay$file) {         if(!$file) core::error (' parameter error ' ); $view _file= Self::$config[' Template_dir '].$file; if( !file_exists($view _file)) Core::error ($view _file. ' template file does not exist ' ); $cache _file= Self::$config[' Cache_dir '].MD5($file); //read content directly from the cache file when the cache file exists and does not expire        if($this->checkcacheexpire ($cache _file, Self::$config[' Cachelefttime ']) ){            Echo $this-ReadFile($cache _file); }Else {            Extract($this-var);//Register Key=value            $view _content=$this-ReadFile($view _file);//Read the file            $view _content=$this->replacetag ($view _content);//Replace label            $temp _file= Self::$config[' Compile_dir '].MD5($file).‘. Htm.php '; $this->writefile ($temp _file,$view _content); Ob_start(); include($temp _file); $content=ob_get_contents(); Ob_end_clean() ; if(Self::$config[' Iscache ']){                                          $this->writefile ($cache _file,$content) ;//the compiled content is written to the cache file            }            Echo $content ; }    }

Then attach the flowchart of this program , as well as the log file of this program.

Postscript

Here is a picture of Brother Bird's frame flowchart.

It is also said that the framework should be called Mvcd,d refers to the data, attach a picture of MVCD, said clearly 1,2,3,4 these steps.

Resources:

Http://www.laruence.com/manual

Https://github.com/linsunny/one

Question:

URL links can also take other parameters as arguments to the action function in addition to the C and a parameters, so parseurl and Initcontroller functions can also be extended.

You can extend the reading of the data through the model and then assign values to the parameters in the view to display.

MVC framework, see again

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.