Understanding MVC framework programming in PHP_PHP tutorial
Jul 15, 2016 pm 01:25 PM
什么是MVC
MVC是一個可以讓你把“三個部分(即MVC的全稱,Model、 View、Controller)”諧調(diào)地組成一個復(fù)雜應(yīng)用程序的概念。一輛汽車就是一個在現(xiàn)實生活中非常好的MVC例子。我們看車都看兩個View(顯 示)部分:內(nèi)部和外部。而這兩個都離不開一個Controller(控制者):司機。剎車系統(tǒng)、方向盤和其他操控系統(tǒng)代表了Model(模型):他們從司 機(Controller)那里取得控制方法然后應(yīng)用到內(nèi)部和外觀(View)。
網(wǎng)絡(luò)上的MVC
MVC框架所涵蓋的概念相當簡單并且極度靈活。基本的概念就是,你有一個單獨的控制器(如index.php)用來控制所有建立在參數(shù)請求基礎(chǔ)上的框架內(nèi)應(yīng)用程序。這個控制器通常包含了(最小程度上)一個定義模型的參數(shù)、一個事件和一個GET參數(shù)。這樣控制器就能確認所有的請求然后運行相應(yīng)的事件。打個 比方來說,一個像這樣/index.php?module=foo&event=bar的請求很有可能就是用來載入一個名叫foo的類,然后運行 foo::bar()[就是其中的bar()函數(shù)]。這樣做的好處有:
一個對應(yīng)所有應(yīng)用程序的接口
同時維護一個應(yīng)用程序內(nèi)無數(shù)的代碼非常麻煩,因為每一段代碼都有自己的相對路徑、數(shù)據(jù)庫鏈接、驗證等等。而這樣做就免除你在這方面的煩惱,允許你合并并重復(fù)使用代碼
為什么要創(chuàng)建自己的MVC框架
迄今為止,我沒有見到過太多用PHP寫的MVC框架。事實上我僅僅知道一個-Solar,是完全用PHP5寫的。另外一個是Cake,一個試圖成為 PHP的RoR(Ruby on Rails-一個Ruby語言開源網(wǎng)絡(luò)框架)。我自己對這兩個框架都有一些不滿意的地方:它們都沒有利用到PEAR,Smarty等所包含的現(xiàn)有代碼;現(xiàn) 在的Cake還比較紊亂;最后,Solar是一個絕大部分由一個人寫的作品(我無意說其作者Paul不是一個好人或者好程序員)。這些問題可能并不會讓你 否認它們,而且很有可能你根本不關(guān)心這些問題。但是正因為如此,我請各位盡可能地審視它們。
老方式
如果回到2001看自己寫的代碼,作者有可能找到一個叫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'); ?> |
只是看這些代碼都會讓我有退縮的欲望。這段代碼的概念就是確保每一個應(yīng)用程序都能適用于這個處理方法,比如我可以簡單地將 template.txt拷進myapp.php,改變一些變量,瞧,它就能運行起來了。盡管如此,這個組織嚴密的處理方法存在一些嚴重的缺點:
如果我的老板想讓作者用myapp.php在一些情況下輸出PDF、一些情況下輸出HTML、一些情況下(直接提交的XML請求)SOAP,我該怎么辦?
如果這個應(yīng)用程序需要IMAP或LDAP驗證,我該怎么辦?
我該如何處理各種不同的代碼(包括編輯、升級和刪除)?
我該如何處理多級驗證(管理員 vs. 非管理員)?
我該如何啟用輸出緩存?
新方式
將所有東西都扔進這個MVC框架,你會發(fā)現(xiàn)生活是如此簡單。請對比以下代碼:
<?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.

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

To merge two PHP arrays and keep unique values, there are two main methods. 1. For index arrays or only deduplication, use array_merge and array_unique combinations: first merge array_merge($array1,$array2) and then use array_unique() to deduplicate them to finally get a new array containing all unique values; 2. For associative arrays and want to retain key-value pairs in the first array, use the operator: $result=$array1 $array2, which will ensure that the keys in the first array will not be overwritten by the second array. These two methods are applicable to different scenarios, depending on whether the key name is retained or only the focus is on

exit() is a function in PHP that is used to terminate script execution immediately. Common uses include: 1. Terminate the script in advance when an exception is detected, such as the file does not exist or verification fails; 2. Output intermediate results during debugging and stop execution; 3. Call exit() after redirecting in conjunction with header() to prevent subsequent code execution; In addition, exit() can accept string parameters as output content or integers as status code, and its alias is die().

The rational use of semantic tags in HTML can improve page structure clarity, accessibility and SEO effects. 1. Used for independent content blocks, such as blog posts or comments, it must be self-contained; 2. Used for classification related content, usually including titles, and is suitable for different modules of the page; 3. Used for auxiliary information related to the main content but not core, such as sidebar recommendations or author profiles. In actual development, labels should be combined and other, avoid excessive nesting, keep the structure simple, and verify the rationality of the structure through developer tools.

There are two ways to create an array in PHP: use the array() function or use brackets []. 1. Using the array() function is a traditional way, with good compatibility. Define index arrays such as $fruits=array("apple","banana","orange"), and associative arrays such as $user=array("name"=>"John","age"=>25); 2. Using [] is a simpler way to support since PHP5.4, such as $color

When you encounter the prompt "This operation requires escalation of permissions", it means that you need administrator permissions to continue. Solutions include: 1. Right-click the "Run as Administrator" program or set the shortcut to always run as an administrator; 2. Check whether the current account is an administrator account, if not, switch or request administrator assistance; 3. Use administrator permissions to open a command prompt or PowerShell to execute relevant commands; 4. Bypass the restrictions by obtaining file ownership or modifying the registry when necessary, but such operations need to be cautious and fully understand the risks. Confirm permission identity and try the above methods usually solve the problem.

The way to process raw POST data in PHP is to use $rawData=file_get_contents('php://input'), which is suitable for receiving JSON, XML, or other custom format data. 1.php://input is a read-only stream, which is only valid in POST requests; 2. Common problems include server configuration or middleware reading input streams, which makes it impossible to obtain data; 3. Application scenarios include receiving front-end fetch requests, third-party service callbacks, and building RESTfulAPIs; 4. The difference from $_POST is that $_POST automatically parses standard form data, while the original data is suitable for non-standard formats and allows manual parsing; 5. Ordinary HTM

InPHP,variablesarepassedbyvaluebydefault,meaningfunctionsorassignmentsreceiveacopyofthedata,whilepassingbyreferenceallowsmodificationstoaffecttheoriginalvariable.1.Whenpassingbyvalue,changestothecopydonotimpacttheoriginal,asshownwhenassigning$b=$aorp

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.
