Implement MVC in php

Source: Internet
Author: User
MVC is becoming increasingly popular in PHP, especially in some open-source frameworks. MVC is sufficient to deal with most situations, but it is not suitable for some situations, such as simple personal blogs and blogs with only a few hundred articles, using MVC makes people think it is too complicated. Similarly, using MVC for portal websites such as Sina will have a large number of files

MVC is becoming increasingly popular in PHP, especially in some open-source frameworks. MVC is sufficient to deal with most situations, but it is not suitable for some situations, such as simple personal blogs and blogs with only a few hundred articles, using MVC makes people think it is too complicated. Similarly, using MVC for portal websites such as Sina will have a large number of files

MVC is becoming increasingly popular in PHP, especially in some open-source frameworks. MVC is sufficient to deal with most situations, but it is not suitable for some situations, such as simple personal blogs and blogs with only a few hundred articles, using MVC makes people think it is too complicated. using MVC for portal websites such as Sina will load a large number of files, which will not affect the speed. Feng Bameng introduces the basic principle and a simple implementation of MVC. The following content is applicable to PHP development.

MVC in PHP

MVC [1] is a software architecture in software engineering. From the php perspective, MVC is somewhat different.

Model, the implementation of application functions, and the implementation of program logic. Responsible for data management and data generation in PHP.

View, graphical interface logic. In PHP, it is responsible for outputting and processing how to call templates and required resource files.

The Controller is responsible for forwarding requests and processing requests. In PHP, the call view and data used are determined based on the request.

Why use MVC

MVC is mainly used to stratify and classify code.

The main purpose of MVC is to solve the separate development and design work in Web development so that its work is relatively independent.

In this process, other advantages are also found. the directory structure of the website is clearer, the website is easier to maintain and expand, and modules can be reused.

MVC request URL

First, the URL of the Request page is implemented in the following structure:

localhost/index.php?c=demo&a=index&param=welcome

If you want to get a more beautiful URL structure, you can optimize the structure, because the URL structure optimization has little to do with this article, and we will share it later.

The preceding parameters show that the accessed file isindex.phpAnd contain three parameters:c,a,param.

MVC directory structure

Then, plan the MVC directory structure as follows:

/* ├ ── Www # website root directory │ ├ ── controller # controller directory │ ├ ── democontroller. php # demo controller │ ├ ── model # model directory │ ├ ── model. php # model │ ├ ── view # view directory │ ├ ── index. php # index view │ ├ ── index. php # entry file */

Controller

Add the following codecontroller/democontroller.phpFile.

 1 // controller/democontroller.php 2 class DemoController 3 { 4     public function index() 5     { 6         echo 'hello world'; 7     } 8 }// End of the class DemoController 9 10 // End of file democontroller.php

This file defines only oneDemoControllerAnd only contains oneindexMethod for outputhello world.

Add the following code to the entry fileindex.phpFile.

1 //index.php2 require('controller/democontroller.php');3 $controller = new DemoController();4 $controller->index();5 6 // End of index.php

Use the aforementioned URL in the browser for access, and you can see the outputhello world. Of course, if the requested URL is not the same, but the same output can also be obtained as shown below.

localhost/index.php?c=abc

It is found that the parameters in the URL have no effect.

If the following URL is used for access, no output is expected.

localhost/controller/democontroller.php

You can see that if you want to access this website and get the correct results, you can only useindex.phpThis is why it is called an entry file. Now, no matter how the parameter can only access the same page, how can we decide to display different results? Or call different controllers?

Improved portal File

The following uses the parameters in the URL to determine which controller to use.

 1 //index.php 2 // get runtime controller prefix 3 $c_str = $_GET['c']; 4 // the full name of controller 5 $c_name = $c_str.'controller'; 6 // the path of controller 7 $c_path = 'controller/'.$c_name.'.php'; 8 // get runtime action 9 $method = $_GET['a'];10 // load controller file11 require($c_path);12 // instantiate controller13 $controller = new $c_name;14 // run the controller  method15 $controller->$method();16 17 // End of index.php

Similarly, use the aforementioned URL in the browser for access, and you can see the outputhello world. The comments in the Code already illustrate the purpose of each step. Of course, you can changecAndaValue to call different controllers and their methods to output different results.

View

The controller is used before, andindex.phpTo dynamically call different controllers. Add the view to separate the display.

1 // view/index.php2 class Index {3     public function display($output) {4         // ob_start();5         echo $output;6     }7 }8 9 // End of index.php

The index. php file in the view directory definesIndexMethod, and only onedisplay()Function that outputs the variables passed to it.
Modify the Controller file.

 1 // controller/democontroller.php 2 class DemoController 3 { 4     private $data = 'Hello furzoom!'; 5     public function index() 6     { 7         //echo 'hello world'; 8         require('view/index.php'); 9         $view = new Index();10         $view->display($data);11     }12 }// End of the class DemoController13 14 // End of file democontroller.php

DefinedataThe index () method does not directly output private variables, but uses view objects to process output. In this case, the output is displayed when you access the service based on the URL specified above:

Hello furzoom!

Different view classes can be called based on different requests to display data in different forms. This will increase the role of the view, the designer can only design the page for the view.

Model

The above seems to be cool, but the content displayed is directly specified in the controller, and you want the content to be specified by the URL, so that the data processing is handed over to the model for processing.

 1 // model/model.php 2 class Model { 3     private $data = array( 4                 'title' => 'Hello furzoom', 5                 'welcome' => 'Welcome to furzoom.com', 6                 ); 7  8     public function getData($key) { 9         return $this->data[$key];10     }11 }12 13 // End of model.php

The View File model. php definesModelClass, the class definesgetData()Is used to return the request data.

Modify the index. php file as follows:

//index.php// get runtime controller prefix$c_str = $_GET['c'];// the full name of controller$c_name = $c_str.'controller';// the path of controller$c_path = 'controller/'.$c_name.'.php';// get runtime action$method = $_GET['a'];// get runtime parameter$param = $_GET['param'];// load controller filerequire($c_path);// instantiate controller$controller = new $c_name;// run the controller  method$controller->$method($param);// End of index.php

Added a parameter$paramAs the method call parameter of the controller.

You also need to modify the Controller method to obtain different data based on different parameters.

 1 // controller/democontroller.php 2 class DemoController 3 { 4     // private $data = 'Hello furzoom!'; 5     function index($param) 6     { 7         // echo 'hello world'; 8         require('view/index.php'); 9         require('model/model.php');10         $model = new Model();11         $view = new Index();12         $data = $model->getData($param);13         $view->display($data);14     }15 }// End of the class DemoController16 17 // End of file democontroller.php

Include the required view files and model files, generate the view and model files, obtain data through the model object, and then output the obtained data using the view object.

In this case, the following output is displayed when you use the aforementioned URL in the browser to access the service:

Welcome to furzoom.com

For example:

Now the MVC mode of PHP has been basically introduced, and the rest of the work is to add and expand as needed. It's easy !!

References

[1] http://zh.wikipedia.org/wiki/MVC

[2] http://blog.chinaunix.net/uid-20761674-id-75075.html

[3] http://wo.zdnet.com.cn/blog-476979-6965.html

[4] http://www.cnblogs.com/cocowool/archive/2009/09/08/1562874.html

Http://furzoom.com/php-instantiate-mvc/ By fengzhu dream

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.