学习封装 MVC (1)

   今天学习了封装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>


    


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值