自己写框架(路由基类、框架基础类、控制器基类)

原创 2019-01-16 17:37:58 245
摘要:路由基类(Route.php) namespace pig; class Route {     protected $route = [];  //路由配置信息     protected $pathinfo = [
路由基类(Route.php)
namespace pig;

class Route
{
    protected $route = [];  //路由配置信息
    protected $pathinfo = []; //pathinfo
    protected $params = []; //url中的参数信息

    public function __construct($route)
    {
        //初始化路由配置
        $this->route = $route;
    }

    //解析路由
    public function parse($queryStr = '')
    {
        //处理查询字符串
        $queryStr = trim(strtolower($queryStr), '/');//将所有字符串猪场转成小写,并过滤两端的正斜线
        $arr = explode('/', $queryStr);//将字符串以正斜线分割存到数组中
        $arr = array_filter($arr, function ($val) {
            if ($val !== '' && $val !== null && $val !== false) return 1;
            return 0;
        });//过滤数组中的空、null、false
        $arr = array_merge($arr);//过滤数组中的空、null、false后保持键值的数字序列

        //解析查询字符串中的内容
        switch (count($arr)) {
            case 0:
                //使用默认模块、控制器、动作
                $this->pathinfo = $this->route;
                break;
            case 1:
                $this->pathinfo['module'] = $arr[0];
                break;
            case 2:
                $this->pathinfo['module'] = $arr[0];
                $this->pathinfo['controller'] = $arr[1];
                break;
            case 3:
                $this->pathinfo['module'] = $arr[0];
                $this->pathinfo['controller'] = $arr[1];
                $this->pathinfo['action'] = $arr[2];
                break;
            default:
                //对参数进行处理(非法路径使用.htaccess文件解决)
                $this->pathinfo['module'] = $arr[0];
                $this->pathinfo['controller'] = $arr[1];
                $this->pathinfo['action'] = $arr[2];

                //获取参数部分,$arr数组第四个索引开始到结束的作为参数处理
                $params = array_slice($arr, 3);
                for ($i = 0; $i < count($params); $i +=2) {
                    //参数成对出现,一个键一个值,
                    //如果参数有值,将该参数以键值对存在参数数组中;如果参数没有值,则放弃该参数
                    if(isset($params[$i + 1]))  $this->params[$params[$i]] = $params[$i + 1];
                }
                break;
        }
        //返回当前对象
        return $this;
    }

    public function dispatch(){
        //模块
        $module = $this->pathinfo['module'];
        //控制器(控制器路径)
        $controller = '\app\\' . $module . '\controller\\' . $this->pathinfo['controller'];
        //动作
        $action = $this->pathinfo['action'];

        //检查控制器中是否存在动作
        if(!method_exists($controller,$action)){
            $action = $this->route['action'];
            header('Location:/');
        }
        //将用户的请求分发到指定的控制器的指定方法上
        return call_user_func_array([new $controller,$action],$this->params);

//        echo $controller,'<br>',$action;
    }

    //获取模型、控制器、动作信息
    public function getPathInfo(){
        return $this->pathinfo;
    }
    //获取模块信息
    public function getModule(){
        return $this->pathinfo['module'] ? : $this->route['module'];
    }
    //获取控制器信息
    public function getController(){
        return '\app\\' . $this->getModule() . '\controller\\' . $this->pathinfo['controller'];
    }

}


框架基础类(Base.php)

namespace pig;


class Base
{
    //配置信息
    protected $config = [];
    //查询字符串
    protected $queryStr = '';

    public function __construct($config, $queryStr = '')
    {
        //初始化配置和查询字符串
        $this->config = $config;
        $this->queryStr = $queryStr;
    }

    //设置调试模式
    public function setDebug()
    {
        if($this->config['app']['debug'] === true){
            error_reporting(E_ALL);//在页面中显示所有错误信息
            ini_set('display_errors','On');//开启错误输出
        }else{
            ini_set('display_errors','Off');//关闭页面显示错误
            ini_set('log_errors','On');//开启错误日志
            ini_set('error_log',BASE_PATH . 'log/error_' . date('YmdHis') . '.log');//设置错误日志存放位置
        }
    }

    //注册自动加载器(自动加载类文件)
    public function loader($class){
        $path = BASE_PATH . str_replace('\\','/',$class) . '.php';

        //检查类文件是否存在
        if(!file_exists($path)){
            header('Location: /');
        }
        require $path;
    }

    //启动框架
    public function run(){
        //调试模式
        $this->setDebug();
        //自动加载(spl_autoload_register():注册给定的函数作为 __autoload 的实现)
        spl_autoload_register([$this,'loader']);
        //请求分发
        echo (new Route($this->config['route']))->parse($this->queryStr)->dispatch();
    }
}

控制器基类(Controller.php)
namespace pig\core;

class Controller
{
    //视图对象
    protected $view = null;
    //实例化视图类
    public function __construct()
    {
        $this->view = new namespace\View();
    }
    //视图模板配置
    public function config(){
        //设置后台模板目录
        $this->view->setDirectory(BASE_PATH . 'app/admin/view');
        //设置后台目录别名(命名空间)
        $this->view->addFolder('admin',BASE_PATH . 'app/admin/view');

        //设置前台模板目录
        $this->view->setDirectory(BASE_PATH . 'app/home/view');
        //设置前台目录别名(命名空间)
        $this->view->addFolder('admin',BASE_PATH . 'app/home/view');
    }

    //模板引擎核心功能:模板赋值、模板渲染
}

视图基类(View.php)
namespace pig\core;

use League\Plates\Engine;

class View extends Engine
{
    //存储变量
    protected $data = [];

    /**
     * View constructor.
     * @param null $directory           当前模板的目录
     * @param string $fileExtension     模板默认扩展名
     */
    public function __construct($directory = null, $fileExtension = 'php')
    {
        parent::__construct($directory, $fileExtension);
    }
}

模型基类(Model.php)
namespace pig\core;

use Medoo\Medoo;

class Model extends Medoo
{
    public function __construct($options = null)
    {
        //加载配置文件
        $config = require "/pig/config.php";
        $options = $config['db'];
        //实例化数据库框架Medoo
        parent::__construct($options);
    }
}


批改老师:韦小宝批改时间:2019-01-16 17:47:23
老师总结:写的非常不错 课后一定要多研究 才能真正的掌握 不过写到这个程度已经非常的不错了

发布手记

热门词条