微调路由,支持请求方式的限制

startmvc php框架学习社区

技术交流社区
微调路由,支持请求方式的限制
mortal 普通会员 时间:2024-09-23 15:45:57 浏览:233

根目录/startmvc/App.php  

在:

$rule = array(

':any' => '.*?',

':num' => '[0-9]+'

);

下修改:

        $this_route = $pathInfo;
		$this_route = explode('/', $this_route);
		$this_route[0] = isset($this_route[0]) && $this_route[0] != '' ? $this_route[0] : config('default_module');
		$this_route[1] = isset($this_route[1]) && $this_route[1] != '' ? $this_route[1] : config('default_controller');
		$this_route[2] = isset($this_route[2]) && $this_route[2] != '' ? $this_route[2] : config('default_action');
		$this_routes = $this_route[0] . DS .$this_route[1] . DS .$this_route[2];
		foreach ($route as $r) {
			if(strpos($r[0],'(:any)') !== false||strpos($r[0],'(:num)') !== false){ 
				$pattern = '#^' . strtr($r[0], $rule) . '$#';//过滤参数
			}else{
				$pattern=$r[0];
			}
			$pathInfo = preg_replace($pattern, $r[1], $pathInfo);
			$r_url = explode('/', $r[1]);
			$r_url[0] = isset($r_url[0]) && $r_url[0] != '' ? $r_url[0] : config('default_module');
		    $r_url[1] = isset($r_url[1]) && $r_url[1] != '' ? $r_url[1] : config('default_controller');
		    $r_url[2] = isset($r_url[2]) && $r_url[2] != '' ? $r_url[2] : config('default_action');
		    $r_urls = $r_url[0] . DS .$r_url[1] . DS .$r_url[2];
			if($this_routes == $r_urls){
			    if(isset($r[2]) && strpos($r[2],':get') !== false){
    		        if(!self::isGet()){
    		            $info = ['code'=>404,'msg'=>'Current access error, please use GET access'];
            			die(json_encode($info));
    		        }
    		    }
    		    if(isset($r[2]) && strpos($r[2],':post') !== false){
    		        if(!self::isPost()){
    		            $info = ['code'=>404,'msg'=>'Current access error, please use POST access'];
            			die(json_encode($info));
    		        }
    		    }
    		    if(isset($r[2]) && strpos($r[2],':ajax') !== false){
    		        if(!self::isAjax()){
    		            $info = ['code'=>404,'msg'=>'Current access error, please use AJAX access'];
            			die(json_encode($info));
    		        }
    		    }
			}
		}

并新增:

可复制/startmvc/Request.php下相同方法


路由即可做到请求方式的限制,代码还可进一步精简,各位共同完善

新路由书写:

//简便方法

['(:any)','home/$1',':get'],//隐藏home模块url并只能get访问

//正则表达式替换替换方法

['/^about$/', 'home/index/about',':get'],

回复列表
1个回复
mortal2024-09-23 03:47:16
文章已重新编辑,之前未使用最新版本,这里做出调整回复