Home  >  Article  >  Backend Development  >  A brief analysis of the MVC pattern and single entry in the PHP framework_PHP tutorial

A brief analysis of the MVC pattern and single entry in the PHP framework_PHP tutorial

WBOY
WBOYOriginal
2016-07-15 13:25:531049browse

关于MVC

这里不详细讲解何为MVC模式,只是简单介绍,关于MVC的具体信息可以去网络上找寻,MVC模式在我理解来它将一个项目分解成三部分,分别是Model(模型),View(视图),Controller(控制器),这三个单词的缩写组合即为MVC.MVC是一种普遍的软件敏捷开发模式,在许多领域特别是桌面编程领域早已经得到了广泛的应用,然而在像php一样的脚本语言中比较难以实现,特别是几年前在脚本语言中很难看到MVC的实现,但是今年随着众多框架的涌现,MVC在各个框架中得到了初步实现,其他框架中的实现方式暂且不提,这里只是介绍codeigniter是如何实现MVC的.

关于单一入口

单一入口指在一个网站(应用程序)中,所有的请求都是指向一个脚本文件的,例如CI中的http:\localhostindex.php,所有对应用程序的访问都是必须通过这个入口,正是单一入口才使得MVC模式得以实现,因为当你访问index.php的时候,应用程序会做大量的初始化工作,调用大量的基础类库,并根据index.php后面的参数加载控制器,然后加载试图,模型等内容信息.

ci的所有文件加载都要经过控制器调用,因为控制器是CI中的超类,也就是其他的类都依附于它,所以用单一入口方式访问CI应用程序的时候,需要在index.php的后面加上控制器名和控制器中的方法名,如果你对于此没有任何概念或者无法理解,可以去CI的官方网站下载它的官方文档,然后详细了解它的工作方式

CI的官方文档非常详尽易懂,这里描述的是文档上所不存在的基本原理部分.

开始

或许应该先讲解CI的控制器是如何工作的,CI中的一个控制器就是用户编写的一个类,它继承自系统的Controller类,例如假设我们要构建一个可以通过http:\localhostindex.phpcontrolfuncparam1param2访问的页面,我们需要做哪些工作呢,首先我们要在systemapplicationcontrollers文件夹下新建一个文件contro.php文件,这个文件即是我们要访问的控制器类所在文件,在此文件中创建以下内容:

1 class Controller extends Controller {<br>2 <br>3     function Controller()<br>4     {<br>5         parent::Controller();    <br>6     }<br>7     <br>8     function func($param1,$param2)<br>9     {<br>10   $this->load->model('MSomemodel','',TRUE);<br>11   $data['data1']= $this->MSomemodel->getvalue();<br>12            $this->load->view('welcome',$data);<br>13     }<br>14 }<br>15 

This is not the basic component of a controller, but an example of a controller that includes model and view.

First of all, note that the class name of the controller should have the first letter capitalized. Then the constructor of the parent class should be called in the constructor of the class, followed by the func() method, which is the second part of the parameters after the url. This method takes two parameters, and the values ​​of these two parameters are It is the value of the third and fourth parts of the url, that is, the access method of the single entrance is actually: http:localhostindex.php controller name method name method parameter 1 method parameter 2...

Each method in the controller class represents a page, that is, many similar operations can be put into a controller to unify the operations

In the above example, func() The other parts of the method load the model and view respectively. When loading the model, the MSomemodel class in the msomemodel.php file in the models folder is loaded. This class is responsible for the model part of the application, which is responsible for the exchange of data. For example, database storage.

Then we executed a method in the model through $data= $this->MSomemodel->getvalue(), returned the data from this method, and then assigned the value to $data[' data1'], $data is an associative array. We pass values ​​to the view file through this array instead of using the common template mode. This method better separates the processing of each part of MVC and has other advantages in terms of performance. A unique aspect.

After that, we pass the $data array to the welcome.php file in the views folder. This file is a regular php and html mixed script. In this script, we can use the passed The $data array outputs information, but please note that you do not need to use $data['data1'] when outputting information in the view file, but only need to echo $data1;.

The basic working method is like this , let’s analyze the implementation from the code level

Code analysis

The Controller class is treated as a super class in CI, that is, all processes that load the MVC implementation pattern Starting from the Controller class, we ignore the previous execution process of CI when it is loaded into this class, and start analyzing directly from the file where the Controller class is located.

The file where the Controller class is located is located in system/libraries/Controller. php file.

In this class, all necessary basic classes are first loaded, including: 'Config', 'Input', 'Benchmark', 'URI', 'Output', 'Language', ' Router' class. Afterwards, the Router class is loaded and its _ci_autoloader() method is executed. This class is the core of the MVC pattern. All other content in the controller is loaded through it. The code is analyzed below:

First let’s look at the _ci_autoloader() method. This function implements automatic loading of certain libraries or classes. If you always use certain classes in your application, but you are not sure that If these classes have been automatically loaded in CI, you can set the library or helper or plugin array to be automatically loaded in the config/autoload.php file. Please refer to the manual for details.

First, take a look at CI How to load libraries. This method allows you to use $this->load->library("name"); anywhere in your controller (usually in the constructor) to load a class. This class can be User-defined classes can also be system class libraries. User-defined classes need to follow CI conventions. For specific information, see the "Create your own class library" section in the manual. The library() method takes a string or a An array of class library names is used as the first parameter. Subsequent processing will traverse and load all classes. You can pass parameters to the constructor of the class to be loaded through the second parameter. The third parameter allows you to define the returned object. The name of , this class loads the class specified by the first parameter. After performing complex path judgment in this class and finding the required class file, the method _ci_init_class($class, '', $params, $object_name is called ); This class is used to instantiate a class. If the above third parameter is included in the statement to load this class, an instance will be returned and this parameter will be used as the instance name. If the third parameter is not set, then it will be returned. An instance name named after the class name. This is why in the previous example, after loading the model, the model class name is used directly as an object.

Let’s look at how CI loads the model later. , this method allows you to use $this->load->model($modelname,$name,$db_conn) to load the model in the controller. These three parameters are the name of the loaded model and the name of the object instantiated after loading. , whether to automatically connect to the database. The last two parameters can be omitted. You can load multiple models at once. You only need to set the first parameter to an array. This method first passes the first parameter with "" Decomposed into an array, this mechanism allows you to create multi-layer folders in the model and arrange the grouping of code more rationally. Then the program takes the last element of the array as the name of the class to be loaded, and searches for this class according to the path. Include this file and instantiate this class. If the second parameter is set, it will be instantiated into the object of $name. Otherwise, the class name will be used as the object name by default.

Let’s look at how CI loads views. The first parameter of the view($view, $vars = array(), $return = FALSE) method is the name of the view to be loaded, and the second parameter is the name of the view to be loaded. The variable value of the view. The third parameter specifies whether to return the data of the output buffer. This method calls the _ci_load($_ci_data) method with all arrays as one array parameter. This method passes the passed variable array through the extract() function. Parse into a symbol table (that is, use the key name as the variable name and the value as the value of the variable), and cache these variables so that variables can be exchanged with each other in different views. This means that this method allows multiple calls. In order to automatically load the variables that have been passed to the previous view every time it is called, all variables passed to the view are cached in an attribute of the class, so that all variables are obtained every time the method is called. Then load this view file, and then assign it to the global variable $OUT as part of the output buffer. This variable is used to control the buffered output. This can improve efficiency and make debugging time more accurate.

Other loading methods The principle is basically the same as the above method, with just a few changes depending on the situation. CI includes all files in the controller in the method of implementing the MVC pattern. After we include these files, we can freely use them in the controller. Objects and data, and then finally output all the data through the buffered output class. Although the structure of the Loader class looks very complicated, its implementation is actually very simple. The internal code principle is basically the same, and it is clear and careful. It’s not difficult to understand if you look at it.


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/446636.htmlTechArticleAbout MVC This is not a detailed explanation of what the MVC pattern is, just a brief introduction. For specific information about MVC, you can go to the Internet Looking, in my understanding, the MVC pattern decomposes a project into three parts, respectively...
Statement:
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