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

In JavaScript, you need to use a custom function to determine whether two arrays are equal, because there is no built-in method. 1) Basic implementation is to compare lengths and elements, but cannot process objects and arrays. 2) Recursive depth comparison can handle nested structures, but requires special treatment of NaN. 3) Special types such as functions and dates need to be considered, and further optimization and testing are required.

Social security number verification is implemented in PHP through regular expressions and simple logic. 1) Use regular expressions to clean the input and remove non-numeric characters. 2) Check whether the string length is 18 bits. 3) Calculate and verify the check bit to ensure that it matches the last bit of the input.

The methods to correctly handle this pointing in JavaScript closures include: 1. Use arrow functions, 2. Use bind methods, 3. Use variables to save this. These methods ensure that this intrinsic function correctly points to the context of the external function.

Using JavaScript to implement data encryption can use the Crypto-JS library. 1. Install and introduce the Crypto-JS library. 2. Use the AES algorithm for encryption and decryption to ensure that the same key is used. 3. Pay attention to the secure storage and transmission of keys. It is recommended to use CBC mode and environment variables to store keys. 4. Consider using WebWorkers when you need high performance. 5. When processing non-ASCII characters, you need to specify the encoding method.

In PHP, the constructor is defined by the \_\_construct magic method. 1) Define the \_\_construct method in the class, which will be automatically called when the object is instantiated and is used to initialize the object properties. 2) The constructor can accept any number of parameters and flexibly initialize the object. 3) When defining a constructor in a subclass, you need to call parent::\_\_construct() to ensure that the parent class constructor executes. 4) Through optional parameters and conditions judgment, the constructor can simulate the overload effect. 5) The constructor should be concise and only necessary initialization should be done to avoid complex logic or I/O operations.

The benefits of using dependency injection (DI) in PHP include: 1. Decoupling, making the code more modular; 2. Improve testability and easy to use Mocks or Stubs; 3. Increase flexibility and facilitate reusing of dependencies; 4. Improve reusability, and the classes can be used in different environments. By passing dependencies externally to objects, DI makes the code easier to maintain and extend.

SendingemailswithPHPisstraightforwardusingthemail()functionormoreadvancedlibrarieslikePHPMailer.1)Usemail()forbasicemails,settingrecipients,subjects,messages,andheaders.2)ForHTMLemails,adjustheaderstospecifyHTMLcontent.3)EmployPHPMailerforenhancedfea

In PHP, you can use the array_product function to calculate the product of all elements in an array. 1) It efficiently processes large data sets and is suitable for calculating portfolio returns and statistical product. 2) Pay attention to the data type, non-numeric elements will be converted to 0. 3) The product of large numbers will be converted to floating point numbers, which may affect the accuracy. 4) For large arrays, the performance is acceptable, but other methods need to be considered when calculating frequently. 5) In financial analysis, it can be used to calculate the total product of percentages.
