返回实现url到类......登陆

实现url到类方法的映射

҈果҈果҈果҈ ҈ ҈2019-05-12 01:31:01263
<?php
/**
*路由、分发类
 */
namespace pig;

class Route
{
//    protected $route = [];
    public $route = [];

//    protected $pathInfo=[];
    public $pathInfo=[];

//    protected $params=[];
    public $params=[];


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

    public function parse($queryStr='')
    {
        $queryStr=trim(strtolower($queryStr),'/');
        $queryArr=explode('/',$queryStr);
        $queryArr=array_filter($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\\'.$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);
    }
}

//引入配置文件
$config=require 'config.php';
//路由配置,默认信息;
$route=new Route($config['route']);
//显示默认模块名,操作名,方法名
var_dump( $route->route);

//解析显示用户提交的模块名,操作名,方法名和参数
var_dump($route->parse($_SERVER['REQUEST_URI']));

//解析出用户提交的模块名,操作名,方法名;
var_dump($route->pathInfo);

FastStoneEditor1.jpg


最新手记推荐

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

全部回复(0)我要回复

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