理解PHP中的MVC編程之MVC框架簡介
【什么是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框架所涵蓋的概念相當(dāng)簡單并且極度靈活。基本的概念就是,你有一個單獨的控制器(如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的文件,它看起來像這樣:www.phpv.net 轉(zhuǎn)載請注明出處
<?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 template
include_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. 非管理員)? 我該如何啟用輸出緩存?www.phpv.net 轉(zhuǎn)載請注明出處
【新方式】
將所有東西都扔進這個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(); }}
?>
注意這段代碼顯然不是用來鏈接到一個數(shù)據(jù)庫、判斷一個用戶是否已經(jīng)登陸、或者輸出任何其他信息。控制器掌握了所有的一切。
如果我想驗證LDAP,我可以建立FR_Auth_LDAP。控制器可以識別某些輸出方法(比如$_GET['output'])并可以隨時轉(zhuǎn)換成PDF或者SOAP。事件處理delete,只負責(zé)刪除,其他的它都不管。因為這個模塊擁有一個FR_User類的實例,它可以簡單地判斷一個用戶是否已經(jīng)登陸等等。Smarty,作為模板引擎控制緩存是理所當(dāng)然的,但是控制器同樣可以控制一部分緩存。
從前面講的老方式到MVC方式對于很多人來講可能是一個全新、陌生的概念,但是一旦你轉(zhuǎn)換到了這樣一個概念,那么要轉(zhuǎn)回去將是件相當(dāng)困難的事情。
【建立底層】
我是一個PEAR尤其是PEAR_Error類的愛好者。PHP5引入了一個新的內(nèi)建類“Exception”取代了PEAR_Error。但是PEAR_Error擁有一些比Exception還要實用的特性。所以,在此系列文章中的MVC框架實例將用到它來做錯誤處理。無論如何,我還是要用到Exception獲得從構(gòu)造器中的錯誤,因為它們本身不能傳回錯誤。
設(shè)計這些基礎(chǔ)類的目的有如下幾點:
利用PEAR快速添加功能到基礎(chǔ)類
建立小巧、可反復(fù)實用的抽象類以便讓使用者在此框架中快速開發(fā)出應(yīng)用程序
用phpDocumentor給所有的基礎(chǔ)類生成文檔
類的層次看起來會像這樣:
-FR_Object將會提供基礎(chǔ)的功能以供其他所有對象使用(包括logging,一般的setFrom(),toArray())
-FR_Object_DB是一個小層面,給子類提供數(shù)據(jù)庫鏈接等功能
-FR_Module是所有應(yīng)用(又稱模塊、模型等等)的底層類
-FR_Auth是所有驗證機制的底層類
·FR_Auth_User是一個驗證類,用來驗證所有需要驗證用戶是否登陸的模塊
·FR_Auth_No是所有不需要驗證的模塊的“假驗證類”
-FR_Presenter是所有用來處理載入和顯示應(yīng)用的底層類
-FR_Presenter_Smarty是包含了載入不同驅(qū)動器能力的顯示層。Smarty是一個非常好的模板類,它擁有內(nèi)建的緩存機制以及一個活躍的開發(fā)團體(譯者注:這分明就是打廣告嘛~)
·FR_Presenter_debug是調(diào)試部分的顯示層。依靠它,開發(fā)者能夠調(diào)試應(yīng)用程序并給他們除錯
·FR_Presenter_rest是一個可以讓開發(fā)者能夠以XML方式輸出應(yīng)用程序的REST顯示層
從以上的基礎(chǔ)類結(jié)構(gòu)上,你應(yīng)該可以看到這個MVC框架的不同部分。FR_Module提供所有模塊所需要的東西,而FR_Presenter則提供不同的顯示方法。在此系列文章中的下一篇中,我將創(chuàng)建控制器將這上面所有的基礎(chǔ)類結(jié)合在一塊。
【代碼標準】
在你正式編寫代碼之前,應(yīng)該坐下來跟你的合伙人(或者你自己)好好討論(或思考)一下代碼標準。MVC編程的整體思想圍繞著兩點:代碼的可再利用性(減少偶合)和代碼的標準化。我推薦至少應(yīng)該考慮到如下幾點:
首先要考慮的是變量命名和縮寫標準。不要因為這個跟你的合作伙伴大吵一通,但是一旦定下來的標準,就要自始至終地遵從,尤其是寫底層代碼(基礎(chǔ)類)的時候。
定制一個標準前綴,用在所有的函數(shù)、類和全局變量上。不走運的是,PHP不支持“namespace(命名空間)”。所以要想避免混淆變量名和發(fā)生的沖突,用一個前綴是個明智的做法。我在整篇文章中將使用“FR_”作為這樣的前綴。
【編寫底層】
文件層次規(guī)劃很重要。基本的層次規(guī)劃很簡單且在一定程度上是嚴格定義的:
/ config.php index.php includes/ Auth.php Auth/ No.php User.php Module.php Object.php Object/ DB.php Presenter.php Presenter/ common.php debug.php smarty.php Smarty/ modules/ example/ config.php example.php tpl/ example.tpl tpl/ default/ cache/ config/ templates/ templates_c/;
你可能會想這樣的文件層次肯定代表了很多的代碼!沒錯,但是你能夠完成它的。在整個系列結(jié)束后,你會發(fā)現(xiàn)你的編程將會變得更簡單并且開發(fā)速度會得到很大的提升。
在文件層次里面,所有的基礎(chǔ)類都在includes文件夾內(nèi)。每一個功能模塊,都用一個配置文件,至少一個模塊文件和一個模板文件。所有的模塊包含在modules文件夾內(nèi)。我已經(jīng)習(xí)慣了將模板文件放在單獨的外部文件夾內(nèi),也就是tpl文件夾。
config.php-中樞配置文件,包含所有的全局配置變量。
index.php-控制器,在接下來的一篇文章中會詳細敘述。
object.php-所有基礎(chǔ)類的底層類,提供絕大部分類需要的功能。FR_Object_DB繼承這個類并提供數(shù)據(jù)庫鏈接。
結(jié)構(gòu)的基本概念就是,讓所有的子類都繼承一個中樞類以便它們都共享一些共同的特性。你完全可以把鏈接數(shù)據(jù)庫的功能放進FR_Object,但是并不是所有類都需要這個功能的,所以FR_Object_DB就有了存在的理由,作者會稍后做出討論它。
<?php require_once('Log.php');
/** * FR_Object * * The base object class for most of the classes that we use in our framework. * Provides basic logging and set/get functionality. * * @author Joe Stump <[email protected]> * @package Framework */
abstract class FR_Object {/*** $log** @var mixed $log Instance of PEAR Log */
protected $log; /*** $me** @var mixed $me Instance of ReflectionClass*/
protected $me; /*** __construct* * @author Joe Stump <[email protected]>* @access public */
public function __construct(){ $this->log = Log::factory('file',FR_LOG_FILE); $this->me = new ReflectionClass($this);}
/*** setFrom** @author Joe Stump <[email protected]>* @access public* @param mixed $data Array of variables to assign to instance* @return void*/
public function setFrom($data) {if (is_array($data) && count($data)) { $valid = get_class_vars(get_class($this)); foreach ($valid as $var => $val) {if (isset($data[$var])) { $this->$var = $data[$var];} }} }
/** * toArray * * @author Joe Stump <[email protected]> * @access public * @return mixed Array of member variables keyed by variable name */
public function toArray() {$defaults = $this->me->getDefaultProperties();$return = array();foreach ($defaults as $var => $val) { if ($this->$var instanceof FR_Object) {$return[$var] = $this->$var->toArray(); } else {$return[$var] = $this->$var; }}
return $return; }
/** * __destruct * * @author Joe Stump <[email protected]> * @access public * @return void */
public function __destruct() {if ($this->log instanceof Log) { $this->log->close();} }}
?>;
auth.php-這是所有驗證功能的底層類。它是從FR_Module里面延伸出來的,主要功能是定義一個基本的驗證類如何工作。
跟FR_Module的道理一樣,有些類不需要鏈接到數(shù)據(jù)庫,那么同理,F(xiàn)R_Auth_No就可以被創(chuàng)建應(yīng)用到不需要驗證功能的類上。
<?php abstract class FR_Auth extends FR_Module {// {{{ __construct()function __construct(){ parent::__construct();}// }}}// {{{ authenticate() abstract function authenticate();// }}}
// {{{ __destruct()
function __destruct() {parent::__destruct(); }// }}} }
?>
module.php-所有模塊的心臟
<?php abstract class FR_Module extends FR_Object_Web {// {{{ properties/*** $presenter** Used in FR_Presenter::factory() to determine which presentation (view)* class should be used for the module.** @author Joe Stump <[email protected]>* @var string $presenter * @see FR_Presenter, FR_Presenter_common, FR_Presenter_smarty*/public $presenter = 'smarty'; /*** $data** Data set by the module that will eventually be passed to the view.** @author Joe Stump <[email protected]>* @var mixed $data Module data* @see FR_Module::set(), FR_Module::getData()*/
protected $data = array();
/*** $name** @author Joe Stump <[email protected]>* @var string $name Name of module class*/
public $name;
/*** $tplFile** @author Joe Stump <[email protected]>* @var string $tplFile Name of template file* @see FR_Presenter_smarty*/
public $tplFile;
/*** $moduleName** @author Joe Stump <[email protected]>* @var string $moduleName Name of requested module* @see FR_Presenter_smarty*/
public $moduleName = null; /*** $pageTemplateFile** @author Joe Stump <[email protected]>* @var string $pageTemplateFile Name of outer page template*/
public $pageTemplateFile = null;// }}}
// {{{ __construct()/*** __construct* * @author Joe Stump <[email protected]>*/
public function __construct(){ parent::__construct(); $this->name = $this->me->getName(); $this->tplFile = $this->name.'.tpl';}
// }}}// {{{ __default()
/*** __default** This function is ran by the controller if an event is not specified* in the user's request.** @author Joe Stump <[email protected]>*/
abstract public function __default();// }}}// {{{ set($var,$val)
/*** set** Set data for your module. This will eventually be passed toe the* presenter class via FR_Module::getData().** @author Joe Stump <[email protected]>* @param string $var Name of variable* @param mixed $val Value of variable* @return void* @see FR_Module::getData()*/
protected function set($var,$val) { $this->data[$var] = $val; }// }}}// {{{ getData()
/*** getData** Returns module's data. ** @author Joe Stump <[email protected]>* @return mixed* @see FR_Presenter_common*/
public function getData(){ return $this->data;}// }}}// {{{ isValid($module)
/*** isValid** Determines if $module is a valid framework module. This is used by* the controller to determine if the module fits into our framework's* mold. If it extends from both FR_Module and FR_Auth then it should be* good to run.** @author Joe Stump <[email protected]>* @static* @param mixed $module* @return bool*/
public static function isValid($module){ return (is_object($module) && $module instanceof FR_Module && $module instanceof FR_Auth);}// }}}// {{{ __destruct()
public function __destruct(){ parent::__destruct();}// }}} } ?>
presenter.php-表述層的核心。
<?php class FR_Presenter {// {{{ factory($type,FR_Module $module)/*** factory** @author Joe Stump <[email protected]>* @access public* @param string $type Presentation type (our view)* @param mixed $module Our module, which the presenter will display* @return mixed PEAR_Error on failure or a valid presenter* @static*/
static public function factory($type,FR_Module $module){ $file = FR_BASE_PATH.'/includes/Presenter/'.$type.'.php'; if (include($file)) {$class = 'FR_Presenter_'.$type;if (class_exists($class)) { $presenter = new $class($module); if ($presenter instanceof FR_Presenter_common) {return $presenter; } return PEAR::raiseError('Invalid presentation class: '.$type);} return PEAR::raiseError('Presentation class not found: '.$type); } return PEAR::raiseError('Presenter file not found: '.$type);}// }}} }
?>;
下一篇里,我將介紹控制器(MVC中的Controller,本文的index.php)的構(gòu)造。第三篇里,我將介紹表述層(MVC里面的View)。第四篇里,我將用具體模塊為例建立一個應(yīng)用(MVC里面的Module或Model)。
