================================
搭建MVC結構
================================
基於MVC,解耦合 (高內聚,低耦合),優點:易維護、易擴展
本MVC模式采用的是單一入口:
如:http://localhost/lamp45/mvc/index.php?m=stu&a=add //打開學生信息的添加界面
其中m的值stu表示訪問的是StuAction a的值add表示是方法(動作)
就是訪問StuAction的add方法。
1. 創建目錄:
ORG 第三方擴展類
model M(模型)層目錄
action A(控制)層目錄
view V(視圖) 層目錄(smarty的模板目錄)
public 公共資源目錄
libs Smarty庫(解壓到這里即可)
view_c Smarty模板編譯目錄
cache Smarty靜態緩存目錄
configs 配置文件目錄
2. 將自己寫好的model類放到model目錄下
model/db.class.php
3. 在ORG目錄下創建一個tpl.class.php的smarty子類,用於初始化smarty(等同於以前的init.php)
代碼如下:
//Smarty信息的初始化類
class Tpl extends Smarty{
public function __construct(){
parent::__construct(); //構造父類
//初始化Smarty對象中屬性:
$this->template_dir = "view"; //smarty模板目錄
$this->compile_dir = "view_c"; //smarty模板編譯目錄
$this->config_dir = "configs"; //smarty配置文件目錄
$this->cache_dir = "cache"; //smarty模板靜態緩存目錄
//$this->caching = true; //是否開啟靜態緩存
//$this->cache_lifetime = 3600; //靜態緩存時間(秒)
//指定定界符
$this->left_delimiter="<{"; //左定界符
$this->right_delimiter="}>"; //右定界符
}
}
4. 在action目錄下創建Action類,繼承Tpl類,文件名叫:action.class.php
代碼如下:
//Action的控制基類
class Action extends Tpl{
public function __construct(){
parent::__construct();
}
/**
*action初始化方法(在這個方法里根據參數a的值決定調用對應的方法)
*
*/
public function init(){
//獲取a參數的值
$a = isset($_GET["a"])?$_GET["a"]:"index"; //默認值為index
//判斷當前Action是否存在此方法
if(method_exists($this,$a)){
//調用此方法
$this->$a();
}else{
die("沒有找到{$a}對應的方法");
}
}
}
5. 在最外層,創建一個index.php的入口文件
<?php
//網站的主入口程序
//自動加載類
function __autoload($name){
$name = strtolower($name);//轉成小寫
if(file_exists("./action/{$name}.class.php")){
require("./action/{$name}.class.php");
}elseif(file_exists("./model/{$name}.class.php")){
require("./model/{$name}.class.php");
}elseif(file_exists("./ORG/{$name}.class.php")){
require("./ORG/{$name}.class.php");
}elseif(file_exists("./libs/".ucfirst($name).".class.php")){
require("./libs/".ucfirst($name).".class.php");
}elseif(file_exists("./libs/sysplugins/{$name}.php")){
require("./libs/sysplugins/{$name}.php");
}else{
die("錯誤:沒有找到對應{$name}類!");
}
}
//數據連接配置文件
require("./configs/config.php");
//獲取參數m的值,並創建對應的Action對象
$mod = isset($_GET['m'])?$_GET['m']:"index";
//拼裝action類名
$classname = ucfirst($mod)."Action";
//創建對應的Action對象
$action = new $classname();
//執行action的初始化(action入口)
$action->init();
6. 在configs的目錄下創建一個config.php的配置文件
7. 測試:
-------------------------------------------------------------
1. 在action目錄下創建一個indexaction.class.php文件
/**
* 網站入口的主Action類
*/
class IndexAction extends Action{
//默認入口方法
public function index(){
$this->assign("title","MVC的測試界面");
$this->display("index.html");
}
}
2. 在view目錄下創建index.html模板頁面
<html>
<head>
<title><{$title}></title>
</head>
<body>
<h2><{$title}></h2>
</body>
</html>
