今天学习了封装MVC框架,给大家分享一下!
一、编写 index 入口文件
1.定义常量
2.加载函数类
3.启动框架
define('BAO',dirname(__FILE__));//获取当前框架目录
define('CORE',BAO.'./core');//获取核心文件
define('APP',BAO.'/app');//获取项目文件路径
define('MODULE','app');//获取项目文件路径
// 开启调试模式 建议开发阶段开启 部署阶段注释或者设为false
define('APP_DEBUG',True);
if(APP_DEBUG){
ini_set('display_error','On');
}else{
ini_set('display_error','Off');
}
//加载函数库
include './core/common/function.php';
//启动框架
include CORE.'/bao.php';
spl_autoload_register('\core\bao::load');
//入口
\core\bao::run();
二、类的自动加载
public static $classMap=array();
static public function load($class){
//判断当前类是否被引用
if(isset($classMap[$class])){
return true;
}else {
$class = str_replace('\\', '\\', $class);
//判断这个路径是否存在
$file=BAO.'/'.$class . '.php';
if (is_file($file)) {
include $file;
self::$classMap[$class]=$class;
} else {
return false;
}
}
}
三、设置路由类
1.隐藏index.php
2.获取URL参数
3.返回对应的控制器和方法
public $ctrl;
public $action;
public function __construct(){
//判断当前URL是否存在
if(isset($_SERVER['REQUEST_URI'])&& $_SERVER['REQUEST_URI']!='/'){
$path=$_SERVER['REQUEST_URI']; //index/index
$pathArr=explode('/',trim($path,'/'));
//判断控制器名
if(isset($pathArr[0])){
$this->ctrl=$pathArr[0];
}
unset($pathArr[0]); //如果存在清除控制器
//判断方法名
if(isset($pathArr[1])){
$this->action=$pathArr[1];
unset($pathArr[1]);//如果存在清除方法
}else{
$this->action='index';//如果不存在默认 index方法
}
//URL多余的部分转换成 get
$count=count($pathArr)+2;
$i=2;
//把 get 过滤成 名 值相对
while($i<$count){
if(isset($pathArr[$i+1])){
$_GET[$pathArr[$i]]=$pathArr[$i+1];
}
$i=$i+2;
};
}else{
$this->ctrl;
$this->action;
}
}
四、配置 .htaccess 文件
1.创建虚拟域名指向自己的框架
2.在框架的根目录中创建 .htaccess 文件
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?/$1 [QSA,PT,L]
</IfModule>