Home >Backend Development >PHP Tutorial >Simple implementation of MVC in php, phpmvc_PHP tutorial

Simple implementation of MVC in php, phpmvc_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:07:59921browse

php simply implements MVC, phpmvc

Using MVC in PHP is becoming more and more popular, especially in some open source frameworks. MVC is sufficient for most situations, but there are some situations where it is not suitable, such as relatively simple personal blogs. For blogs with only a few hundred articles, using MVC feels a bit too complicated; similarly for blogs with only a few hundred articles, MVC is not suitable for most situations. For portal websites such as Sina, using MVC, a large number of files will be loaded, and the impact on speed is unacceptable. Maple Bamboo Dream introduces the basic principles of MVC and a simple implementation. The following introduction is suitable for PHP development.

MVC in PHP

MVC[1] is a software architecture in software engineering. From a PHP perspective, MVC is a little different.

Model (model), the realization of program application functions and the realization of program logic. Responsible for data management and data generation in PHP.

View, graphical interface logic. Responsible for output in PHP, handling how to call templates and required resource files.

Controller (controller) is responsible for forwarding requests and processing requests. In PHP, the view to be called and the data to be used are determined based on the request.

Why use MVC

The main function of MVC is to layer and classify code.

The main purpose of MVC is to solve the problem of separating development and design work in Web development, making the work relatively independent.

During this process, we also discovered some other advantages. The directory structure of the website is clearer, the website is easier to maintain and expand, and modules can be reused.

MVC implementation

Request URL

First, agree on the URL when requesting the page, and implement it with the following structure:

Copy code The code is as follows:

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

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

As can be seen from the above parameters, the file accessed is index.php, which also contains three parameters: c, a, and param.

MVC Directory Structure

Next, plan the directory structure of MVC as follows:

Copy code The code is as follows:

/*
├─www​​​​​​​​​​​​​​​​ │ ├─controller # Controller directory
│ │ ├─democontroller.php # demo controller
│ ├─model                                                                               │ │ ├─model.php           # model model
│ ├─view                                                                                                                        │ │ ├─index.php # index view
│ ├─index.php # Entry file
*/



controller

Add the following code to the controller/democontroller.php file.

Copy code

The code is as follows: // controller/democontroller.php
class DemoController
{
Public function index()
{
echo 'hello world';
}
}//End of the class DemoController
// End of file democontroller.php



Only one DemoController class is defined in this file, and it only contains an index method for outputting hello world.
Add the following code to the entry file index.php file.

Copy code

The code is as follows: //index.php
require('controller/democontroller.php');
$controller = new DemoController();
$controller->index();
// End of index.php



Use the above agreed URL to access in the browser and see the output hello world. Of course, if the URL you request is not like that, but as shown below, you can get the same output.

Copy code

The code is as follows: localhost/index.php?c=abc

It was found that the parameters in the URL have no effect yet.

If you use the URL below to access it, you can expect that there will be no output.

Copy code The code is as follows:

localhost/controller/democontroller.php

You can see that if you want to access this website and get the correct results, you can currently only access it through index.php, which is why it is called the entry file. Now you can only access the same page regardless of the parameters, so how do you decide to display different results? Or what about calling a different controller?

Improve entry file

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

Copy code The code is 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'];
// load controller file
require($c_path);
// instantiate controller
$controller = new $c_name;
// run the controller method
$controller->$method();
// End of index.php

Similarly use the above agreed URL to access in the browser and see the output hello world. Comments in the code explain the purpose of each step. Of course, you can call different controllers and their methods by changing the c and a values ​​in the URL parameters to output different results.

View View

We just used the controller controller before, and dynamically called different controllers in the entry file index.php. Then joining the view will show the separation.

Copy code The code is as follows:

// view/index.php
class Index {
Public function display($output) {
                  // ob_start();
             echo $output;
}
}
// End of index.php

The Index method is defined in the index.php file in the view directory, and there is only one display() function, which is responsible for outputting the variables passed to it.
Modify the controller file below.

Copy code The code is as follows:

// controller/democontroller.php
class DemoController
{
      private $data = 'Hello furzoom!';
Public function index()
{
//echo 'hello world';
​​ require('view/index.php');
$view = new Index();
$view->display($data);
}
}//End of the class DemoController
// End of file democontroller.php

A data private variable is defined in the controller. The index() method no longer outputs directly, but uses the view object to process the output. At this point, when accessing according to the agreed URL above, you will see the output:

Hello furzoom!
Different view classes can be called according to different requests to display data in different forms. This will increase the role of the view, and designers can design the page only for the view.

Model

The above seems to be very cool, but what kind of content is displayed is directly specified in the controller. It is hoped that the content is also specified by the URL, so that the data processing is handed over to the model.

Copy code The code is as follows:

// model/model.php
class Model {
      private $data = array(
'title' => 'Hello furzoom',
                 'welcome' => 'Welcome to furzoom.com',
);
Public function getData($key) {
            return $this->data[$key];
}
}
// End of model.php

The view file model.php defines a Model class, which defines a getData() method to return the requested data.

Also modify the entry file index.php as follows:

Copy code The code is 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 file
require($c_path);
// instantiate controller
$controller = new $c_name;
// run the controller method
$controller->$method($param);
// End of index.php

Added a parameter $param and used it as a method call parameter of the controller.

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

Copy code The code is as follows:

// controller/democontroller.php
class DemoController
{
// private $data = 'Hello furzoom!';
Function index($param)
{
// echo 'hello world';
          require('view/index.php');
​​ require('model/model.php');
$model = new Model();
$view = new Index();
$data = $model->getData($param);
$view->display($data);
}
}//End of the class DemoController
// End of file democontroller.php

Contains the required view files and model files, then generates the view and model files, then obtains the data through the model object, and then uses the view object to output the obtained data.

At this time, use the above agreed URL to access in the browser, and you will get the following output:

Welcome to furzoom.com
As shown below:

At this point, the MVC model of PHP has been basically introduced. The remaining work is to add and expand it as needed. It is very simple! !

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/954099.htmlTechArticlephp simply implements MVC, phpmvc using MVC in PHP is becoming more and more popular, especially in some open source frameworks among. MVC is sufficient for most situations, but there are some situations where it is not suitable...
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