- 論壇徽章:
- 0
|
這是一篇介紹如何用php來實現(xiàn)MVC模式開發(fā)的文件。
這是一篇介紹如何用php來實現(xiàn)MVC模式開發(fā)的文件。關(guān)于MVC模式的技術(shù)文章網(wǎng)上隨處可以,所以這篇文件將不再講述這種模式的優(yōu)缺點(實際
上是我說不清楚),子講他的php技術(shù)實現(xiàn)。并且在以后的系列文章中也是以講技術(shù)為主。
一、實現(xiàn)統(tǒng)一的網(wǎng)站入口(在MVC中調(diào)用Controler層的方法,也就是控制層)
大家也許經(jīng)常在網(wǎng)上看到這樣的路徑(http://www.aaa.com/aaa/bbb/aaa?id=5),讓人不解,這樣的網(wǎng)站的實現(xiàn)方式有幾種可能性:
1、隱藏文件的擴展名,對這種做法的好處,眾說紛紜,不過個人覺得沒有必要;
2、用了網(wǎng)站的重定向規(guī)則,實現(xiàn)虛擬路徑;
3、強制文件解析的方式,實現(xiàn)虛擬路徑。
用第23種方法可以實現(xiàn)網(wǎng)站的統(tǒng)一接口,合理的整合網(wǎng)站,更好的體現(xiàn)網(wǎng)站的安全性和架構(gòu),用這兩種方式的網(wǎng)站大多是使用“MVC”模式構(gòu)
建和實現(xiàn)的。
下面是一個例子
訪問路徑如下:
....../test/*******/Bad
....../test/*******/Good
(其中的"******"可以用任何字符串替換,"......."是你的web路徑)
文件的目錄結(jié)構(gòu)如下
|-- .htaccess
|-- test
|-- Application.php
|-- Controler/GoodControler.php
|-- Controler/BadControler.php
注意 文件".htaccess",在windows下不能直接建立的,可以在命令行模式下建立.
文件0:(.htaccess)(這個文件是更改apache的配置方式用的)
forcetype application/x-httpd-php
文件1:(test.php)
parse();
$aa->go();
?>
文件2:(GoodControler.php)
文件3:(BadControler.php)
文件4:(Application.php)
_parsePath();
$this->_getControlerFile();
$this->_getControlerClassname();
}
/*
* 解析當(dāng)前的訪問路徑,得到要進(jìn)行動作
*/
function _parsePath(){
list($path, $param) = explode("?", $_SERVER["REQUEST_URI"]);
$pos = strrpos($path, "/");
$this->action = substr($path, $pos+1);
}
/*
* 通過動作$action,解析得到該$action要用到的controler文件的路徑
*/
function _getControlerFile(){
$this->controlerFile = "./Controler/".$this->action."Controler.php";
if(!file_exists($this->controlerFile))
die("Controler文件名(".$this->controlerFile.")解析錯誤");
require_once $this->controlerFile;
}
/*
* 通過動作$action,解析得到該$action要用到的controler類名
*/
function _getControlerClassname(){
$this->controlerClass = $this->action."Controler";
if(!class_exists($this->controlerClass))
die("Controler類名(".$this->controlerClass.")解析錯誤");
}
/*
* 調(diào)用controler,執(zhí)行controler的動作
*/
function go(){
$c = new $this->controlerClass();
$c->control();
}
}
?>
本文來自ChinaUnix博客,如果查看原文請點:http://blog.chinaunix.net/u/12228/showart_62245.html |
|