原理
地址格式:www.****.com/index.php?c=ctrl&a=action
通过地址栏中的c和a来确定需要用到的控制器和方法,缺省了默认index控制器和index方法
目录结构
www
-controller //控制器目录
--indexController.php //控制器文件名格式
-view //模板文件目录
--index //前台页面的模板
---index.html //模板文件名格式
--admin //后台模板
-model //模型文件
--msgModel.php //模型文件名格式
-core //核心文件
--model.php //模型类
--database.php //数据库配置
--function.php //函数
--config.php //配置文件
--session.php //session设置
-index.php //入口文件
以留言板为例开发MVC框架
前台
用户登录后留言,可以留言、回复留言、查看留言
用户不能给自己回复
后台
管理用户,管理留言,管理员
入口文件index.php
<?php
include './core/config.php'; //把所有要用到的文件引入
$c = isset($_GET['c']) ? $_GET['c'] : 'index'; //判断地址中有没有c参数,如果没有设为默认index
$controller = $c .'Controller'; //组合控制器文件
$c_name = $controller.'.php';
$c_path = './controller/'.$c_name;
if(!file_exists($c_path)){ //如果控制器文件不存在则提示错误
echo $c.'控制器不存在,请检查';
exit;
}
include $c_path;
$ctrl = new $controller;
$m_path = './model/'.$c.'Model.php';
if(file_exists($m_path)){
include $m_path;
$model = new $c.'Model';
}
$a = isset($_GET['a']) ? $_GET['a'] : 'index'; //判断地址中有没有a参数,如果没有设为默认index
$ctrl->$a(); //执行方法
数据库的配置database.php
<?php
return [
'dbhost'=>'localhost',
'dbuser'=>'root',
'dbpwd'=>'root',
'dbname'=>'msg',
'dbchar'=>'utf8',
];
?>
使用时
<?php
class Db{
protected $dbConfig;
protected $conn;
function __construct(){
$this->dbConfig = include("database.php");
$this->conn = mysql_connect($this->dbConfig['dbhost'],$this->dbConfig['dbuser'],$this->dbConfig['dbpwd']);
mysql_select_db($this->dbConfig['dbname']);
mysql_query("SET NAMES {$this->dbConfig['dbchar']}");
}
public function getBySql($sql){
$result = mysql_query($sql,$this->conn);
$num_rows = mysql_num_rows($result);
if($num_rows>1){
while($rows = mysql_fetch_assoc($result)){
$row[]=$rows;
}
}else{
$row = mysql_fetch_assoc($result);
}
return $row;
}
}
可以定义一个组合地址的函数
function tourl($url){
if(stripos($url, '/')){
$str = explode('/',$url);
$urlstr = '/index.php?c='.$str[0].'&a='.$str[1];
}else{
$c = isset($_GET['c']) ? $_GET['c'] : 'index';
$urlstr = '/index.php?c='.$c.'&a='.$url;
}
return $urlstr;
}
使用方法:在模板中写 <?php echo tourl('add');?>或<?php echo tourl('index/add');?>
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




