search
HomeBackend DevelopmentPHP TutorialPHP - MVC pattern explanation and examples

1. MVC pattern flow chart

PHP - MVC pattern explanation and examples

##2. MVC concept

(1) Function

MVC includes Controller, Model, and View.

The function of the controller is to call the model and the view, pass the data generated by the model to the view, and let the view display it

The function of the model is to obtain the data and process the returned data

The function of the view is to beautify the obtained data and output it to the user terminal

(2) Execution process

1. Viewer-> Call the controller and issue instructions

2. Controller-> Select the appropriate model according to the command

3. Model-> Get data according to the command

4. Controller-> Select the view according to the command

5 . View -> Display the obtained data

3. Simple MVC example

(1) Directory planning

PHP - MVC pattern explanation and examples

(2) Writing class files

1. testController.class.php Controller class file

Naming rules :test (name)Controller (controller file).class.php (class file)

<!-- 
 首先实例化控制器对象,并调用指令方法,
 方法里面实例化模型对象,调用取数据方法
 并实例化视图对象,调用展示方法
  -->
  <!-- 
 控制器的方法没有参数,而其他的就有参数
   -->
<?php
    // 类名和文件名相同 
    class testController{
        function show(){
            
            $testModel = new testModel();//按指令选择一个模型
            $data = $testModel -> get();//模型按照指令取数据
            //按指令选择视图 实例化一个view的对象
            $testView  = new testView();
            //把取到的数据按用户的样子显示出来
            $testView -> display($data);
        }
    }
?>

2. testModel.class.php Model class file

Naming rules: test (model file name) Model ( Model file).class.php Class file

<?php 
    class testModel{
        //获取数据
        function get(){
            return "hello world";
        }
    }
?>

3. testView.class.php View class file

<?php 
    class testView{
        //展示数据
        function display($data){
            echo $data;
        }
    }
?>

4. Single entry file

Let him call the controller , and the controller calls the model and view

<?php
//引入类文件
require_once(&#39;/libs/Controller/testController.class.php&#39;);
require_once(&#39;/libs/Model/testModel.class.php&#39;);
require_once(&#39;/libs/View/testView.class.php&#39;);
 
//类的实例化
$testController = new testController();//对象赋值给变量
$testController->show();//调用方法
?>

5. Running results

PHP - MVC pattern explanation and examples

4. Simple MVC instance improvement----Method Encapsulation

1. Encapsulate an object that instantiates a controller, etc. and a function that calls a method

<?php
 
    //控制器名字和要执行的方法
    function C($name,$method){
        require_once(&#39;/libs/Controller/&#39;.$name.&#39;Controller.class.php&#39;);
        //对象赋值给变量
        // $testController = new testController();
        // $testController->show();
        eval(&#39;$obj = new &#39;.$name.&#39;Controller();$obj->&#39;.$method.&#39;();&#39;);//把字符串转换为可执行的php语句
    }
    //封装一个实例化模型的对象和调用方法的函数
    function M($name){
        require_once(&#39;/libs/Model/&#39;.$name.&#39;Model.class.php&#39;);
        //$testModel = new testModel();
        eval(&#39;$obj = new &#39;.$name.&#39;Model();&#39;);//实例化
        return $obj;
    }
 
    //封装一个实例化视图的对象和调用方法的函数
    function V($name){
        require_once(&#39;/libs/View/&#39;.$name.&#39;View.class.php&#39;);
            //$testView  = new testView();
            eval(&#39;$obj = new &#39;.$name.&#39;View();&#39;);
            return $obj;
    }
 
    //为了安全性 ,过滤函数
    //addslashes对’,字符进行转义
    //get_magic_quotes_gpc()当前魔法符号的打开状态,打开返回true,
    function daddslashes($str){
        return (!get_magic_quotes_gpc() )? addslashes($str) : $str;
    }
?>

2. Rewrite the entry file index.php

Browser URL access form http://...index.php?controller=controller name&method=method name

<?php 
require_once(&#39;function.php&#39;);
 
//允许访问的控制器名和方法名的数组
$controllerAllow=array(&#39;test&#39;,&#39;index&#39;);
$methodAllow =array(&#39;test&#39;,&#39;index&#39;,&#39;show&#39;);
//用get方式接收url中的参数
//过滤输入非法字符  并判断是否在数组里
$controller = in_array($_GET[&#39;controller&#39;],$controllerAllow )? daddslashes($_GET[&#39;controller&#39;]) :&#39;index&#39; ;
$method = in_array($_GET[&#39;method&#39;],$methodAllow) ? daddslashes($_GET[&#39;method&#39;]) :&#39;index&#39;;
//调用控制器和执行方法
C($controller,$method);
 
?>

3. Running results

Browser access http:// localhost:8080/MVC/index.php?controller=test&method=show Show hello world

PHP - MVC pattern explanation and examples

If you want to know more about PHP related issues, please visit the PHP Chinese website:

PHP Video tutorial

The above is the detailed content of PHP - MVC pattern explanation and examples. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

What is autoloading in PHP?What is autoloading in PHP?Apr 30, 2025 pm 03:37 PM

Autoloading in PHP automatically loads class files when needed, improving performance by reducing memory use and enhancing code organization. Best practices include using PSR-4 and organizing code effectively.

What are PHP streams?What are PHP streams?Apr 30, 2025 pm 03:36 PM

PHP streams unify handling of resources like files, network sockets, and compression formats via a consistent API, abstracting complexity and enhancing code flexibility and efficiency.

What is the maximum size of a file that can be uploaded using PHP ?What is the maximum size of a file that can be uploaded using PHP ?Apr 30, 2025 pm 03:35 PM

The article discusses managing file upload sizes in PHP, focusing on the default limit of 2MB and how to increase it by modifying php.ini settings.

What is Nullable types in PHP ?What is Nullable types in PHP ?Apr 30, 2025 pm 03:34 PM

The article discusses nullable types in PHP, introduced in PHP 7.1, allowing variables or parameters to be either a specified type or null. It highlights benefits like improved readability, type safety, and explicit intent, and explains how to declar

What is the difference between the unset() and unlink() functions ?What is the difference between the unset() and unlink() functions ?Apr 30, 2025 pm 03:33 PM

The article discusses the differences between unset() and unlink() functions in programming, focusing on their purposes and use cases. Unset() removes variables from memory, while unlink() deletes files from the filesystem. Both are crucial for effec

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software