之前,我们已经认识了MVC,以及MVC的入门
今天,我们开始搭建一个可以使用的MVC框架(1-3)
1. 首先是入口文件
入口文件,一个项目所有的方法都是从这个文件中加载进去的
首先,定义常量,方便以后的调用,然后开启我们的DEBUG模式,以便开发使用。
然后,引入一些类库文件,即核心文件。
最后,使整个框架跑起来
<?php
define('LTY',realpath('./'));//当前项目的目录
define('CORE',LTY.'/core');//框架的核心文档所处的目录
define('APP',LTY.'/app');//我们的项目目录
define('MODULE','app'); //自定义的
define('DEBUG',true); //默认开启BEBUG模式
if(DEBUG){
ini_set('display_error','On');
}else{
ini_set('display_error','Off');
}
include CORE.'/common/function.php'; //引入我们自己的自定义函数类
include CORE.'/tian.php'; //加载我们的核心文件
\core\tian::run(); //运行框架
?>
2. 类的自动加载
访问的时候会自动加载已经设置好的类,方法。
在核心文件中添加load方法,即自动加载
static public function load($class){
//自动加载类库;
if(isset($classMap[$class])){//判断是已经引入类库
return true;
}else{
$class = str_replace('\\', '/', $class);
$file = LTY.'/'. $class.'.php';
if (is_file($file)) {//如果加数组载成功,就加入到存放类库的中
include $file;
self::$classMap[$class]=$class;
}else{
return false;
}
}
}
$classMap为存放已经引入的类库中,在开始定义
public static $classMap = array();
其中在入口文件中还需要加入
spl_autoload_register('\core\tian::load'); //自动加载类,调用一个不存在的类的时候会调用他
3. 路由类
通过一个入口接受请求, 然后通过(URL)匹配规则将请求分发到不同的地方。
创建lib文件夹,用来存放外部的类文件
新建route.php 其中加入以下代码
<?php
namespace core\lib;
class route{
public $ctrl;
public $action;
public function __construct(){
// p('route ok');
/*
*隐藏index.php
*获取URL 参数部分
* 返回对应控制器和方法
* */
//p($_SERVER);
if(isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI']!='/'){
$path=$_SERVER['REQUEST_URI'];
$patharr=explode('/',trim($path,'/'));
if(isset($patharr[0])){//这里来隐藏index.php和index
$this->ctrl=$patharr[0];
}
unset($patharr[0]);
if(isset($patharr[1])){
$this->action=$patharr[1];
unset($patharr[1]);
}else{
$this->action='index';
}
//p($patharr);die;
//把url多余的部分转换成GET;
$count = count($patharr) + 2;
$i = 2;
while($i<$count){
if(isset($patharr[$i+1])){
$_GET[$patharr[$i]] = $patharr[$i+1];
}
$i = $i +2;
}
//p($_GET);die;
}else{
$this->ctrl='index';
$this->action='index';
}
}
}