search
HomeBackend DevelopmentPHP Tutorial浅析PHP程序设计中的MVC编程思想_PHP

MVC

PHP的MVC编程思想目前已经被广泛使用于各种大型项目的开发,很多成熟的MVC框架也逐渐被大家所熟知并被广泛应用于各类项目中,比较常见的如ThinkPHP、codeigniter、Symfony、yii、cakePHP等等。本文就来简述一下php的MVC程序设计思想。

一、什么是MVC

简单的说就是将网站源码分类、分层。
MVC三个字母的含义:
M:Model 模型,负责数据库操作。
V:View 视图,负责调用Model调取数据,再调用模板,展示出最终效果。
C:Controller 控制器,程序的入口,决定改调用哪个View,并告诉View该做什么。
如此说来,程序的执行顺序是C-V-M 或 C-M ,和MVC的名字正好相反。

二、为什么要MVC

1.能使网站程序物理结构更合理。

当用PHP建设一个网站的时候,最笨的方法,你可能把每个页面建成一个PHP文件。如果你的网站只有index.php,menu.php.article.php 三个页面,那你可以不用MVC,但我们做一般的网站的时候,动辄几十个页面,把所有页面放在根目录显然不是我们所能接受的,于是你需要一个合理的思想去将你的代码分类,按功能把他们分成不同的目录,且由程序智能的载入调用,这就是MVC要帮助你做的。

2.使代码更容易维护。

我们再来看单个页面,最笨的方法,就是PHP代码与HTML代码混合,这显然不够好,你在维护网站的时候不得不区分哪里是PHP,哪里是HTML,这对于一个程序员来说,简直是灾难。于是很多人就使用Smarty,这样就可以将“数据处理”与“页面展示”分开来,这样做的确不错,也有很多人正在这么做,但这还不是MVC,MVC要做的就是将“数据处理”再分为“逻辑处理”与“数据库操作”,这就是所说的分层。
这样当你的程序错误或想要修改的时候,就变得很轻松了,当页面显示错误的时候,你就去检查V或模板文件;当逻辑有问题的时候,你就去检查C和V;当你数据库操作错误就去检查M。
其实MVC一般要把PHP的一个页面分割为4个页面,分别是C,V,M,模板。各司其职,方便管理。

3.有利于代码复用。

MVC会把一般会把一个大的功能放在一个目录下,也就是由一个C去管理。
例如要做一个含有会员系统的网站,我们就可以把会员相关的代码都放到user目录里,由User_Controller统一管理,当我们另一个网站也需要会员系统的时候,我们就可以直接把这个目录复制过去,修改一下接口就可以了。

三、PHP实现MVC的思路

我们需要三个基类:Controller、View、Model ,然后不同的C、V、M分别继承他们就有对应的属性与方法了,如果这里你不理解,可以去看看面向对象的书。

这里给大家提供一种MVC基类的设计思路,仅供参考:

1. Controller类的设计

一个main()方法,供程序调用,主要是通过get和post变量决定该如何处理。
一个getModel($model)方法,在需要调用数据库的时候,调用对应目录的M。
一个display($view)方法,在main()方法中调用,载入对应的V,并掉应V的main()方法;

2.View类的设计与Controller很相似

一个main()方法,当C载入V的时候调用这个方法,使程序能继续执行下去。
一个getModel($model)方法,在需要调用数据库的时候,调用对应目录的M。
一个display($template),调用对应的模板文件,并把数据传递给模板。

3.Model类的设计

可以定义一些属性,例如要操作那些表,操作那些字段等。
一个getDB()方法,获得一个数据库类的实例,(数据库类一般都是用单件模式设计的)
一个load()方法,载入一个数据。
一个add()方法,可以根据定义好的属性自动构造SQL语句,并执行插入操作。
一个eidt()方法,同上,但执行修改操作。
一个del()方法,同上,但执行删除操作。
为了能使新手更好的理解我这个思路的工作原理,我们现在模拟一个用户登录的场景,看看MVC是如何工作的。
现在假设,所有的数据都提交给index.php,

第一步:
我们提交各get变量,告诉index.php该用哪个C,例如可以这样index.php?controller=user
然后index接收到get变量,什么也不需要做,直接找到/user/controller.php,把所有数据丢给他,本来GET和POST就是全局的,所以index.php也不需要做什么,直接调用C的main函数就可以了,到此index.php的任务完成。

第二步:
C的main函数开始执行,检查变量,发现用户要执行的登录操作(很简单,你post个变量do=login就可以了),于是调用getModel,载入对应的M类(例如/user/models/model.php),并实例化, 调用实例的load方法,载入该用户的数据资料,判断是否与用户提交的密码一致,如果提交的数据不正确header跳转到出错页面,如果正确,调用display()方法,载入对应的V(例如/user/views/details.php),并实例化,调用其main()函数,进入第三步。到此C的任务已完成,第二不操作均在main函数中进行。

第三步:
你可以选择调用getModel()载入M,重写调取数据,也可以在C实例化V的时候,把参数传过来(例如SESSION),当V已经确定得到数据以后,display(),载入模板,MVC执行完毕。
当然,由于字数与精力限制,这里写的只是非常简要的概括,实际实施的时候要考虑很多细节,但我设计MVC的时候,大概思路就是这样,也用到了实际中,感觉良好。

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
PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

Debunking the Myths: Is PHP Really a Dead Language?Debunking the Myths: Is PHP Really a Dead Language?Apr 16, 2025 am 12:15 AM

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

The PHP vs. Python Debate: Which is Better?The PHP vs. Python Debate: Which is Better?Apr 16, 2025 am 12:03 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

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

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.