smarty建的mvc环境

 

================================
搭建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>

 

posted @ 2018-04-18 21:12  阿波罗任先生  阅读(141)  评论(0编辑  收藏  举报