返回路由的解析与分......登陆

路由的解析与分发

关超2019-06-04 19:02:12222
<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/4
 * Time: 17:50
 */

class Route{

    protected $route = [];

    public $pathInfo = [];

    public $params = [];

    public function __construct($route)
    {
        $this->route=$route;
    }

    //解析路由
    public function parse($queryStr=''){
        //去除前后/
        $queryStr = trim(strtolower($queryStr),'/');
        //切割
        $queryArr = explode('/',$queryStr);

        $queryArr = array_filter($queryArr);

        //解析出queryArr的模块、控制器、操作、参数
        switch (count($queryArr)){
            //如果没有指向默认控制器
            case 0:
                $this->pathInfo = $this->route;
                break;

            case 1:
                $this->pathInfo['module']=$queryArr[0];
                break;

            case 2:
                $this->pathInfo['module']=$queryArr[0];
                $this->pathInfo['controller']=$queryArr[1];
                break;

            case 3:
                $this->pathInfo['module']=$queryArr[0];
                $this->pathInfo['controller']=$queryArr[1];
                $this->pathInfo['action']=$queryArr[2];
                break;

                //如果是非法或者不存在的访问
            default:
                $this->pathInfo['module']=$queryArr[0];
                $this->pathInfo['controller']=$queryArr[1];
                $this->pathInfo['action']=$queryArr[2];

            $arr = array_slice($queryArr,3);

            for($i = 0;$i<count($arr);$i+=2){
                //如果没有第二个参数,则放弃
                if (isset($arr[$i+1])) {
                    $this->params[$arr[$i]] = $arr[$i+1];
                }
            }
            break;
        }

        return $this;

    }

    //请求分发
    public function dispatch(){
        $module = $this->pathInfo['module'];
        $controller='app\\'.$module.'\controller\\'. ucfirst($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);

    }

}


//测试路由
$queryStr = $_SERVER['QUERY_STRING'];

echo $queryStr;
echo '<hr>';

echo '<pre>';
print_r(explode('/',$queryStr));

echo '<hr>';

$config = require 'config.php';
$route = new Route($config['route']);

$route->parse($queryStr);
print_r($route->pathInfo);
print_r($route->params);


最新手记推荐

• 用composer安装thinkphp框架的步骤• 省市区接口说明• 用thinkphp,后台新增栏目• 管理员添加编辑删除• 管理员添加编辑删除

全部回复(0)我要回复

暂无评论~
  • 取消回复发送