Home Backend Development PHP Tutorial PHP implements simple MVC

PHP implements simple MVC

Oct 12, 2019 pm 04:03 PM
mvc php

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 (recommended learning: PHP video tutorial)

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 (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 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:

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

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:

 /*
 ├─www                       # 网站根目录
 │  ├─controller             # 控制器目录
 │  │  ├─democontroller.php  # demo控制器
 │  ├─model                  # 模型目录
 │  │  ├─model.php           # model模型
 │  ├─view                   # 视图目录
 │  │  ├─index.php           # index视图
 │  ├─index.php              # 入口文件
 */
Copy after login

Controller controller

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

 // controller/democontroller.php
 class DemoController
 {
     public function index()
     {
     echo 'hello world';
     }
 }// End of the class DemoController
 // End of file democontroller.php
Copy after login

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.

 //index.php
 require('controller/democontroller.php');
 $controller = new DemoController();
 $controller->index();
 // End of index.php
Copy after login

Use the above agreed URL in the browser to access 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.

localhost/index.php?c=abc
Copy after login

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

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

localhost/controller/democontroller.php
Copy after login

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 the entry file

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

  //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
Copy after login

Similarly use the above agreed URL in the browser to access 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.

ViewView

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

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

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.

 // 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
Copy after login

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 time, when accessing according to the above agreed URL, you will see the output:

Hello furzoom!
Copy after login

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. I hope the content is also specified by the URL, so Leave the data processing to the model.

 // 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
Copy after login

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

At the same time, modify the entry file index.php 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
Copy after login

Add a parameter $param and use 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.

 // 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
Copy after login

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

此时,在浏览器中使用上面的约定的URL进行访问,将得到输出如下:

Welcome to furzoom.com
Copy after login

至此PHP的MVC模式已经基本介绍完成了,剩余的工作就是根据需要进行添加扩充了,很简单吧!!

The above is the detailed content of PHP implements simple MVC. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles