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

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

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

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

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

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

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

老方式

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

<?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)行起來(lái)了。盡管如此,這個(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 to access a character in a string by index in PHP How to access a character in a string by index in PHP Jul 12, 2025 am 03:15 AM

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

How to prevent session hijacking in PHP? How to prevent session hijacking in PHP? Jul 11, 2025 am 03:15 AM

To prevent session hijacking in PHP, the following measures need to be taken: 1. Use HTTPS to encrypt the transmission and set session.cookie_secure=1 in php.ini; 2. Set the security cookie attributes, including httponly, secure and samesite; 3. Call session_regenerate_id(true) when the user logs in or permissions change to change to change the SessionID; 4. Limit the Session life cycle, reasonably configure gc_maxlifetime and record the user's activity time; 5. Prohibit exposing the SessionID to the URL, and set session.use_only

PHP get the first N characters of a string PHP get the first N characters of a string Jul 11, 2025 am 03:17 AM

You can use substr() or mb_substr() to get the first N characters in PHP. The specific steps are as follows: 1. Use substr($string,0,N) to intercept the first N characters, which is suitable for ASCII characters and is simple and efficient; 2. When processing multi-byte characters (such as Chinese), mb_substr($string,0,N,'UTF-8'), and ensure that mbstring extension is enabled; 3. If the string contains HTML or whitespace characters, you should first use strip_tags() to remove the tags and trim() to clean the spaces, and then intercept them to ensure the results are clean.

PHP get the last N characters of a string PHP get the last N characters of a string Jul 11, 2025 am 03:17 AM

There are two main ways to get the last N characters of a string in PHP: 1. Use the substr() function to intercept through the negative starting position, which is suitable for single-byte characters; 2. Use the mb_substr() function to support multilingual and UTF-8 encoding to avoid truncating non-English characters; 3. Optionally determine whether the string length is sufficient to handle boundary situations; 4. It is not recommended to use strrev() substr() combination method because it is not safe and inefficient for multi-byte characters.

How to URL encode a string in PHP with urlencode How to URL encode a string in PHP with urlencode Jul 11, 2025 am 03:22 AM

The urlencode() function is used to encode strings into URL-safe formats, where non-alphanumeric characters (except -, _, and .) are replaced with a percent sign followed by a two-digit hexadecimal number. For example, spaces are converted to signs, exclamation marks are converted to!, and Chinese characters are converted to their UTF-8 encoding form. When using, only the parameter values ??should be encoded, not the entire URL, to avoid damaging the URL structure. For other parts of the URL, such as path segments, the rawurlencode() function should be used, which converts the space to . When processing array parameters, you can use http_build_query() to automatically encode, or manually call urlencode() on each value to ensure safe transfer of data. just

How to set and get session variables in PHP? How to set and get session variables in PHP? Jul 12, 2025 am 03:10 AM

To set and get session variables in PHP, you must first always call session_start() at the top of the script to start the session. 1. When setting session variables, use $_SESSION hyperglobal array to assign values ??to specific keys, such as $_SESSION['username']='john_doe'; it can store strings, numbers, arrays and even objects, but avoid storing too much data to avoid affecting performance. 2. When obtaining session variables, you need to call session_start() first, and then access the $_SESSION array through the key, such as echo$_SESSION['username']; it is recommended to use isset() to check whether the variable exists to avoid errors

How to prevent SQL injection in PHP How to prevent SQL injection in PHP Jul 12, 2025 am 03:02 AM

Key methods to prevent SQL injection in PHP include: 1. Use preprocessing statements (such as PDO or MySQLi) to separate SQL code and data; 2. Turn off simulated preprocessing mode to ensure true preprocessing; 3. Filter and verify user input, such as using is_numeric() and filter_var(); 4. Avoid directly splicing SQL strings and use parameter binding instead; 5. Turn off error display in the production environment and record error logs. These measures comprehensively prevent the risk of SQL injection from mechanisms and details.

See all articles