1.4.1 MVC框架模式的實(shí)現(xiàn)(2)
1.4.1 MVC框架模式的實(shí)現(xiàn)(2)
步驟3:創(chuàng)建Controllers/DefaultController.php文件,創(chuàng)建控制器DefaultController繼承父類CController,創(chuàng)建首頁(yè)管理方法actionIndex(),在其中創(chuàng)建模型Article對(duì)象,并調(diào)用find()方法獲取數(shù)據(jù),渲染視圖,并把數(shù)據(jù)輸出到視圖頁(yè)面。
- <?php
- require '../framework/CController.php';//導(dǎo)入框架文件
- require '../models/Article.php';//導(dǎo)入文章表模型類文件
- class DefaultController extends CController
- {
- //首頁(yè)管理
- public function actionIndex()
- {
- //創(chuàng)建模型對(duì)象
- $article=new Article();
- //獲得數(shù)據(jù)
- $result=$article->find();
- //渲染視圖,并把數(shù)據(jù)輸出到視圖頁(yè)面
- $this->render("../views/index.php",array("result"=>$result));
- }
- //列表頁(yè)管理
- public function actionList(){}
- //內(nèi)容頁(yè)管理
- public function actionArticle(){}
- }
- $default_con = new DefaultController();
- $default_con->actionIndex();
- ?>
步驟4:創(chuàng)建views/index.php,在視圖文件中,對(duì)查詢結(jié)果變量$result進(jìn)行循環(huán)處理,生成完整的HTML頁(yè)面。
- <DIV class="rightList2 marginbtm15">
- <UL class=ulRightList1s>
- <?php
- foreach ($result as $row)
- {
- ?>
- <li><A title=<?php echo $row["title"]; ?> href="#"
- target=_blank><?php echo $row["title"];?></A></li>
- <?php
- }
- ?>
- </UL>
- </DIV>
實(shí)現(xiàn)的MVC框架執(zhí)行流程如圖1-5所示。
1.用戶直接調(diào)用控制器實(shí)例對(duì)象。控制器調(diào)用類中的action方法(動(dòng)作)。
2.控制器調(diào)用模型實(shí)例對(duì)象從數(shù)據(jù)庫(kù)中讀取數(shù)據(jù)。
3.渲染視圖。
4.視圖讀取并顯示模型的屬性。
5.動(dòng)作完成視圖渲染并將其返回給用戶。
本節(jié)按照MVC框架模式的工作思想,完成了控制器、模型、視圖3個(gè)部分的代碼分離。我們?cè)L問程序,需要去訪問controllers目錄下的控制器文件,這樣做存在明顯的設(shè)計(jì)缺陷。如果控制器文件較多,則會(huì)導(dǎo)致系統(tǒng)結(jié)構(gòu)訪問混亂,并存在后期維護(hù)困難、安全性差等一系列問題,而且不便于系統(tǒng)的統(tǒng)一管理。
下一節(jié)將新增入口文件,通過(guò)解析用戶請(qǐng)求的URL,提取出控制器名和動(dòng)作方法名,創(chuàng)建相應(yīng)控制器實(shí)例對(duì)象,并執(zhí)行動(dòng)作方法。
喜歡的朋友可以添加我們的微信賬號(hào):
51CTO讀書頻道二維碼
51CTO讀書頻道活動(dòng)討論群:365934973