国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Backend Development PHP Tutorial Understanding MVC framework programming in PHP_PHP tutorial

Understanding MVC framework programming in PHP_PHP tutorial

Jul 15, 2016 pm 01:25 PM
model mvc php What Can yes frame understand of programming

什么是MVC

MVC是一個(gè)可以讓你把“三個(gè)部分(即MVC的全稱,Model、 View、Controller)”諧調(diào)地組成一個(gè)復(fù)雜應(yīng)用程序的概念。一輛汽車就是一個(gè)在現(xiàn)實(shí)生活中非常好的MVC例子。我們看車都看兩個(gè)View(顯 示)部分:內(nèi)部和外部。而這兩個(gè)都離不開一個(gè)Controller(控制者):司機(jī)。剎車系統(tǒng)、方向盤和其他操控系統(tǒng)代表了Model(模型):他們從司 機(jī)(Controller)那里取得控制方法然后應(yīng)用到內(nèi)部和外觀(View)。

網(wǎng)絡(luò)上的MVC

MVC框架所涵蓋的概念相當(dāng)簡(jiǎn)單并且極度靈活?;镜母拍罹褪牵阌幸粋€(gè)單獨(dú)的控制器(如index.php)用來控制所有建立在參數(shù)請(qǐng)求基礎(chǔ)上的框架內(nèi)應(yīng)用程序。這個(gè)控制器通常包含了(最小程度上)一個(gè)定義模型的參數(shù)、一個(gè)事件和一個(gè)GET參數(shù)。這樣控制器就能確認(rèn)所有的請(qǐng)求然后運(yùn)行相應(yīng)的事件。打個(gè) 比方來說,一個(gè)像這樣/index.php?module=foo&event=bar的請(qǐng)求很有可能就是用來載入一個(gè)名叫foo的類,然后運(yùn)行 foo::bar()[就是其中的bar()函數(shù)]。這樣做的好處有:

一個(gè)對(duì)應(yīng)所有應(yīng)用程序的接口

同時(shí)維護(hù)一個(gè)應(yīng)用程序內(nèi)無數(shù)的代碼非常麻煩,因?yàn)槊恳欢未a都有自己的相對(duì)路徑、數(shù)據(jù)庫鏈接、驗(yàn)證等等。而這樣做就免除你在這方面的煩惱,允許你合并并重復(fù)使用代碼

為什么要?jiǎng)?chuàng)建自己的MVC框架

迄今為止,我沒有見到過太多用PHP寫的MVC框架。事實(shí)上我僅僅知道一個(gè)-Solar,是完全用PHP5寫的。另外一個(gè)是Cake,一個(gè)試圖成為 PHP的RoR(Ruby on Rails-一個(gè)Ruby語言開源網(wǎng)絡(luò)框架)。我自己對(duì)這兩個(gè)框架都有一些不滿意的地方:它們都沒有利用到PEAR,Smarty等所包含的現(xiàn)有代碼;現(xiàn) 在的Cake還比較紊亂;最后,Solar是一個(gè)絕大部分由一個(gè)人寫的作品(我無意說其作者Paul不是一個(gè)好人或者好程序員)。這些問題可能并不會(huì)讓你 否認(rèn)它們,而且很有可能你根本不關(guān)心這些問題。但是正因?yàn)槿绱?,我?qǐng)各位盡可能地審視它們。

老方式

如果回到2001看自己寫的代碼,作者有可能找到一個(gè)叫template.txt的文件,它看起來像這樣:

<?php require_once('config.php'); // Other requires, DB info, etc. $APP_DB = 'mydb';$APP_REQUIRE_LOGIN = false; // Set to true if script requires login$APP_TEMPLATE_FILE = 'foo.php'; // Smarty template$APP_TITLE = "My Application"; if ($APP_REQUIRE_LOGIN == true) {if (!isset($_SESSION['userID'])) {header("Location: /path/to/login.php");exit();}} $db = DB::connect('mysql://'.$DB_USER.':'.$DB_PASS.'@localhost/'.$APP_DB);if (!PEAR::isError($db)) {$db->setFetchMode(DB_FETCHMODE_ASSOC);} else {die($db->getMessage());} // Put your logic here // Output the templateinclude_once(APP_TEMPLATE_PATH.'/header.php');include_once(APP_TEMPLATE_PATH.'/'.$APP_TEMPLATE_FILE);include_once(APP_TEMPLATE_PATH.'/footer.php'); ?>

只是看這些代碼都會(huì)讓我有退縮的欲望。這段代碼的概念就是確保每一個(gè)應(yīng)用程序都能適用于這個(gè)處理方法,比如我可以簡(jiǎn)單地將 template.txt拷進(jìn)myapp.php,改變一些變量,瞧,它就能運(yùn)行起來了。盡管如此,這個(gè)組織嚴(yán)密的處理方法存在一些嚴(yán)重的缺點(diǎn):

如果我的老板想讓作者用myapp.php在一些情況下輸出PDF、一些情況下輸出HTML、一些情況下(直接提交的XML請(qǐng)求)SOAP,我該怎么辦?

如果這個(gè)應(yīng)用程序需要IMAP或LDAP驗(yàn)證,我該怎么辦?

我該如何處理各種不同的代碼(包括編輯、升級(jí)和刪除)?

我該如何處理多級(jí)驗(yàn)證(管理員 vs. 非管理員)?

我該如何啟用輸出緩存?

新方式

將所有東西都扔進(jìn)這個(gè)MVC框架,你會(huì)發(fā)現(xiàn)生活是如此簡(jiǎn)單。請(qǐng)對(duì)比以下代碼:

<?php class myapp extends FR_Auth_User{public function __construct(){parent::__construct();} public function __default(){// Do something here} public function delete(){ } public function __destruct(){parent::__destruct();}} ?>

Note that this code is obviously not used to link to a database, determine whether a user is logged in, or output any other information. The controller has it all.

If I want to authenticate to LDAP, I can set up FR_Auth_LDAP. The controller can recognize certain output methods (such as $_GET['output']) and can convert to PDF or SOAP at any time. The event handler delete is only responsible for deletion and does not care about anything else. Because this module has an instance of the FR_User class, it can simply determine whether a user has logged in, etc.

Smarty, as a template engine, controls the cache as a matter of course, but the controller can also control part of the cache.

From the old way mentioned above to the MVC way may be a new and unfamiliar concept to many people, but once you switch to such a concept, it will be quite difficult to switch back.


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/446665.htmlTechArticleWhat is MVC? MVC is a tool that allows you to combine "three parts (that is, the full name of MVC, Model, View, Controller)" concepts that harmoniously compose a complex application. A car is a...
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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

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)

How do I stay up-to-date with the latest PHP developments and best practices? How do I stay up-to-date with the latest PHP developments and best practices? Jun 23, 2025 am 12:56 AM

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

What is PHP, and why is it used for web development? What is PHP, and why is it used for web development? Jun 23, 2025 am 12:55 AM

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

How to set PHP time zone? How to set PHP time zone? Jun 25, 2025 am 01:00 AM

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

How do I validate user input in PHP to ensure it meets certain criteria? How do I validate user input in PHP to ensure it meets certain criteria? Jun 22, 2025 am 01:00 AM

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

What is data serialization in PHP (serialize(), unserialize())? What is data serialization in PHP (serialize(), unserialize())? Jun 22, 2025 am 01:03 AM

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom

How do I embed PHP code in an HTML file? How do I embed PHP code in an HTML file? Jun 22, 2025 am 01:00 AM

You can embed PHP code into HTML files, but make sure that the file has an extension of .php so that the server can parse it correctly. Use standard tags to wrap PHP code, insert dynamic content anywhere in HTML. In addition, you can switch PHP and HTML multiple times in the same file to realize dynamic functions such as conditional rendering. Be sure to pay attention to the server configuration and syntax correctness to avoid problems caused by short labels, quotation mark errors or omitted end labels.

What are the best practices for writing clean and maintainable PHP code? What are the best practices for writing clean and maintainable PHP code? Jun 24, 2025 am 12:53 AM

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

How do I execute SQL queries using PHP? How do I execute SQL queries using PHP? Jun 24, 2025 am 12:54 AM

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas

See all articles