🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] * * * * * #1 路由解析 >>路由解析的实现在(library/Route.php)中 >路由 将Url分派到指定的应用处理逻辑部分。 >>Url路由 主要包括路由注册与路由检测两部分 >路由注册 注册Url路由规则到Route中 >路由检测 根据Route解析网络请求Url到应用处理逻辑部分。 >注册路由规则 , 指的是 (请求对象的url)与(应用层的应用地址)的对应关系 >路由规则的解析,就是在注册的路由规则中查找请求对象url,对应的应用地址。 >由 [应用组织](http://www.kancloud.cn/zmwtp/tp/210988) 章节可知,tp将应用组织为6种类型,在路由规则中,可以注册5种类型的应用地址(module,controller,method,function,redirect,)为url的对应处理逻辑。 #2 路由规则 >> 路由规则主要实现Url信息与应用地址信息的关联 >Url信息 主要是网络请求的Url参数信息。如域名,请求类型,请求的控制器,操作,url参数等 >应用地址信息 主要是应用层对应的Url处理逻辑地址标识信息。 >根据应用组织的不同类型应用表示为不同形式的应用地址格式。 >路由规则的注册形式 包括配置文件注册,Route对应方法注册。 >配置文件的注册的实现分为加载路由配置文件,然后调用Route对应的注册方法。 ## 2-1 Url信息 >> Url信息可以由网络请求对象(Request)的对应方法获取 >具有信息查看[网络请求(Request)](http://www.kancloud.cn/zmwtp/tp/210989)章节 ## 2-2 应用地址信息 >> 应用地址信息 根据不同形式的应用类型分为以下5种 >模块/控制器地址 >重定向地址 >控制器方法 >类的方法 >闭包函数 ### 1 模块/控制器类应用地址 >> 模块/控制器应用是最为常见的基础应用类型。 > 模块/控制器地址格式为 [模块/控制器]操作?参数1=值1&参数2=值2... ~~~ ; 配置文件格式 'blog/:id'=>'blog/read', 'blog/:id'=>'index/blog/read', 'blog/:id'=>'blog/read?status=1&app_id=5', ;Route方法格式 Route::rule('blog/:id','blog/read'); Route::rule('blog/:id','index/blog/read'); Route::rule('blog/:id','blog/read?status=1&app_id=5'); ~~~ ### 2 重定向类应用地址 >>重定向应用必须以"/"或者"http"开头 ~~~ ; 重定向地址格式 'blog/:id'=>'/blog/read/id/:id' 'blog/:id'=>'http://blog.thinkphp.cn/read/:id' Route::rule('blog/:id','/blog/read/id/:id'); Route::rule('blog/:id','http://blog.thinkphp.cn/read/:id'); ~~~ ### 3 控制器操作类应用地址 >> Url信息直接解析到特定控制器的操作地址 >格式为:@[模块/控制器/]操作 ~~~ 'blog/:id'=>'@index/blog/read', Route::rule('blog/:id','@index/blog/read'); ~~~ ### 4 类的方法类应用地址 >>Url信息解析到类的方法 >格式为:\类的命名空间\类名@方法名或者\类的命名空间\类名::方法名 ~~~ 'blog/:id'=>'\app\index\service\Blog@read', 'blog/:id'=>'\app\index\service\Blog::read', Route::rule('blog/:id',''\app\index\service\Blog@read'); Route::rule('blog/:id',''\app\index\service\Blog::read'); ~~~ ### 5 闭包函数类应用地址 >> Url信息直接执行闭包函数应用 > 将闭包函数作为参数 ~~~ Route::get('hello',function(){ return 'hello,world!'; }); Route::get('hello/:name',function($name){ return 'Hello,'.$name; }); ~~~ ## 2-3 注册形式 ### 配置文件注册 >>配置文件注册在application/route.php中定义 ~~~ return [ 'new/:id' => 'News/read', 'blog/:id' => ['Blog/update',['method' => 'post|put'], ['id' => '\d+']], ]; ~~~ ### Route方法注册 >>配置文件中也可以使用Route方法进行注册 >最后需要返回一个数组作为配置文件的返回内容 ~~~ ;Route方法注册路由 Route::rule([ ['blog/:id','Blog/read',['method'=>'get']], ['blog/:id','Blog/update',['method'=>'post']], ... ],'','*',['ext'=>'html'],['id'=>'\d+']); ~~~ ~~~ ;两种形式路由注册 use think\Route; Route::rule('hello/:name','index/index/hello'); return [ 'new/:id' => 'News/read', 'blog/:id' => ['Blog/update',['method' => 'post|put'], ['id' => '\d+']], ]; ~~~ >配置文件的位置可以自定义如下 ~~~ // 定义路由配置文件(数组) 'route_config_file' => ['route', 'route1', 'route2'], ~~~ #3 路由注册 >>路由规则的注册按照层次分为三个类型 >类型注册 >注册核心 >参数选项 ## 3-1 类型注册 ### get类型 ~~~ public static function get($rule, $route = '', $option = [], $pattern = []) { self::rule($rule, $route, 'GET', $option, $pattern); } ~~~ ### post类型 ~~~ public static function get($rule, $route = '', $option = [], $pattern = []) { self::rule($rule, $route, 'GET', $option, $pattern); } ~~~ ### put类型 ~~~ public static function put($rule, $route = '', $option = [], $pattern = []) { self::rule($rule, $route, 'PUT', $option, $pattern); } ~~~ ### delete类型 ~~~ public static function delete($rule, $route = '', $option = [], $pattern = []) { self::rule($rule, $route, 'DELETE', $option, $pattern); } ~~~ ### any类型 ~~~ public static function any($rule, $route = '', $option = [], $pattern = []) { self::rule($rule, $route, '*', $option, $pattern); } ~~~ ### patch类型 ~~~ public static function patch($rule, $route = '', $option = [], $pattern = []) { self::rule($rule, $route, 'PATCH', $option, $pattern); } ~~~ ### resource类型 ~~~ public static function resource($rule, $route = '', $option = [], $pattern = []) { if (is_array($rule)) { foreach ($rule as $key => $val) { if (is_array($val)) { list($val, $option, $pattern) = array_pad($val, 3, []); } self::resource($key, $val, $option, $pattern); } } else { if (strpos($rule, '.')) { // 注册嵌套资源路由 $array = explode('.', $rule); $last = array_pop($array); $item = []; foreach ($array as $val) { $item[] = $val . '/:' . (isset($option['var'][$val]) ? $option['var'][$val] : $val . '_id'); } $rule = implode('/', $item) . '/' . $last; } // 注册资源路由 foreach (self::$rest as $key => $val) { if ((isset($option['only']) && !in_array($key, $option['only'])) || (isset($option['except']) && in_array($key, $option['except']))) { continue; } if (isset($last) && strpos($val[1], ':id') && isset($option['var'][$last])) { $val[1] = str_replace(':id', ':' . $option['var'][$last], $val[1]); } elseif (strpos($val[1], ':id') && isset($option['var'][$rule])) { $val[1] = str_replace(':id', ':' . $option['var'][$rule], $val[1]); } $item = ltrim($rule . $val[1], '/'); self::rule($item . '$', $route . '/' . $val[2], $val[0], $option, $pattern); } } } ~~~ ### miss类型 ~~~ public static function miss($route, $method = '*', $option = []) { self::rule('__miss__', $route, $method, $option, []); } ~~~ ### auto类型 ~~~ public static function auto($route) { self::rule('__auto__', $route, '*', [], []); } ~~~ ##3-2 注册核心 >>各种类型的路由注册最后都会调用路由的注册核心(Route::rule()) >Route::rule()会进一步调用注册的实现Route::setRule() ### Route::rule() ~~~ public static function rule($rule, $route = '', $type = '*', $option = [], $pattern = []) { $group = self::getGroup('name'); if (!is_null($group)) { // 路由分组 $option = array_merge(self::getGroup('option'), $option); $pattern = array_merge(self::getGroup('pattern'), $pattern); } $type = strtoupper($type); if (strpos($type, '|')) { $option['method'] = $type; $type = '*'; } if (is_array($rule) && empty($route)) { foreach ($rule as $key => $val) { if (is_numeric($key)) { $key = array_shift($val); } if (is_array($val)) { $route = $val[0]; $option1 = array_merge($option, $val[1]); $pattern1 = array_merge($pattern, isset($val[2]) ? $val[2] : []); } else { $route = $val; } self::setRule($key, $route, $type, isset($option1) ? $option1 : $option, isset($pattern1) ? $pattern1 : $pattern, $group); } } else { self::setRule($rule, $route, $type, $option, $pattern, $group); } } ~~~ ### Route::setRule() ~~~ protected static function setRule($rule, $route, $type = '*', $option = [], $pattern = [], $group = '') { if (is_array($rule)) { $name = $rule[0]; $rule = $rule[1]; } elseif (is_string($route)) { $name = $route; } if (!isset($option['complete_match'])) { if (Config::get('route_complete_match')) { $option['complete_match'] = true; } elseif ('$' == substr($rule, -1, 1)) { // 是否完整匹配 $option['complete_match'] = true; $rule = substr($rule, 0, -1); } } elseif (empty($option['complete_match']) && '$' == substr($rule, -1, 1)) { // 是否完整匹配 $option['complete_match'] = true; $rule = substr($rule, 0, -1); } if ('/' != $rule) { $rule = trim($rule, '/'); } $vars = self::parseVar($rule); if (isset($name)) { self::name($name, [$rule, $vars, self::$domain]); } if ($group) { if ('*' != $type) { $option['method'] = $type; } if (self::$domain) { self::$rules['domain'][self::$domain]['*'][$group]['rule'][] = ['rule' => $rule, 'route' => $route, 'var' => $vars, 'option' => $option, 'pattern' => $pattern]; } else { self::$rules['*'][$group]['rule'][] = ['rule' => $rule, 'route' => $route, 'var' => $vars, 'option' => $option, 'pattern' => $pattern]; } } else { if ('*' != $type && isset(self::$rules['*'][$rule])) { unset(self::$rules['*'][$rule]); } if (self::$domain) { self::$rules['domain'][self::$domain][$type][$rule] = ['rule' => $rule, 'route' => $route, 'var' => $vars, 'option' => $option, 'pattern' => $pattern]; } else { self::$rules[$type][$rule] = ['rule' => $rule, 'route' => $route, 'var' => $vars, 'option' => $option, 'pattern' => $pattern]; } if ('*' == $type) { // 注册路由快捷方式 foreach (['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'] as $method) { if (self::$domain) { self::$rules['domain'][self::$domain][$method][$rule] = true; } else { self::$rules[$method][$rule] = true; } } } } } ~~~ ## 3-3 参数选项 #4 注册扩展 >>路由注册还包含其他各种扩展信息 >域名的注册 >路由分组注册 >路由的绑定注册 >路由的快捷注册 >路由变量规则 >rest方法规则修改 >路由别名注册 ## 4-1 domain域名注册 >域名注册包括域名注册接口(Route::domain())和域名注册实现(Route::setDomain()) ### 1 Route::domain() ~~~ public static function domain($domain, $rule = '', $option = [], $pattern = []) { if (is_array($domain)) { foreach ($domain as $key => $item) { self::domain($key, $item, $option, $pattern); } } elseif ($rule instanceof \Closure) { // 执行闭包 self::setDomain($domain); call_user_func_array($rule, []); self::setDomain(null); } elseif (is_array($rule)) { self::setDomain($domain); self::group('', function () use ($rule) { // 动态注册域名的路由规则 self::registerRules($rule); }, $option, $pattern); self::setDomain(null); } else { self::$rules['domain'][$domain]['[bind]'] = [$rule, $option, $pattern]; } } ~~~ ### Route::setDomain() ~~~ private static function setDomain($domain) { self::$domain = $domain; } ~~~ ## 4-2 路由分组 >> 路由分组的注册包括路由分组接口(Route::group())和路由分组实现核心(Route::setGroup()) ### Route::group() ~~~ public static function group($name, $routes, $option = [], $pattern = []) { if (is_array($name)) { $option = $name; $name = isset($option['name']) ? $option['name'] : ''; } // 分组 $currentGroup = self::getGroup('name'); if ($currentGroup) { $name = $currentGroup . ($name ? '/' . ltrim($name, '/') : ''); } if (!empty($name)) { if ($routes instanceof \Closure) { $currentOption = self::getGroup('option'); $currentPattern = self::getGroup('pattern'); self::setGroup($name, array_merge($currentOption, $option), array_merge($currentPattern, $pattern)); call_user_func_array($routes, []); self::setGroup($currentGroup, $currentOption, $currentPattern); if ($currentGroup != $name) { self::$rules['*'][$name]['route'] = ''; self::$rules['*'][$name]['var'] = self::parseVar($name); self::$rules['*'][$name]['option'] = $option; self::$rules['*'][$name]['pattern'] = $pattern; } } else { $item = []; foreach ($routes as $key => $val) { if (is_numeric($key)) { $key = array_shift($val); } if (is_array($val)) { $route = $val[0]; $option1 = array_merge($option, isset($val[1]) ? $val[1] : []); $pattern1 = array_merge($pattern, isset($val[2]) ? $val[2] : []); } else { $route = $val; } $options = isset($option1) ? $option1 : $option; $patterns = isset($pattern1) ? $pattern1 : $pattern; if ('$' == substr($key, -1, 1)) { // 是否完整匹配 $options['complete_match'] = true; $key = substr($key, 0, -1); } $vars = self::parseVar($key); $item[] = ['rule' => $key, 'route' => $route, 'var' => $vars, 'option' => $options, 'pattern' => $patterns]; // 设置路由标识 self::name($route, [$key, $vars, self::$domain]); } self::$rules['*'][$name] = ['rule' => $item, 'route' => '', 'var' => [], 'option' => $option, 'pattern' => $pattern]; } foreach (['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'] as $method) { if (!isset(self::$rules[$method][$name])) { self::$rules[$method][$name] = true; } elseif (is_array(self::$rules[$method][$name])) { self::$rules[$method][$name] = array_merge(self::$rules['*'][$name], self::$rules[$method][$name]); } } } elseif ($routes instanceof \Closure) { // 闭包注册 $currentOption = self::getGroup('option'); $currentPattern = self::getGroup('pattern'); self::setGroup('', array_merge($currentOption, $option), array_merge($currentPattern, $pattern)); call_user_func_array($routes, []); self::setGroup($currentGroup, $currentOption, $currentPattern); } else { // 批量注册路由 self::rule($routes, '', '*', $option, $pattern); } } ~~~ ### Route::setGroup() ~~~ public static function setGroup($name, $option = [], $pattern = []) { self::$group['name'] = $name; self::$group['option'] = $option ?: []; self::$group['pattern'] = $pattern ?: []; } ~~~ ## 4-3 路由绑定注册 >>路由绑定注册将当前url绑定到特定命名空间(namespace),模块(module),类(class),控制器(controller) >包括路由绑定接口(Route::bind())和各种类型绑定(Route::bindToxx()) ### Route::bind() ~~~ public static function bind($bind, $type = 'module') { self::$bind = ['type' => $type, $type => $bind]; } ~~~ ### Route::bindToNamespace() ~~~ public static function bindToNamespace($url, $namespace, $depr = '/') { $array = explode($depr, $url, 3); $class = !empty($array[0]) ? $array[0] : Config::get('default_controller'); $method = !empty($array[1]) ? $array[1] : Config::get('default_action'); if (!empty($array[2])) { self::parseUrlParams($array[2]); } return ['type' => 'method', 'method' => [$namespace . '\\' . $class, $method]]; } ~~~ ### Route::bindToModule() ~~~ public static function bindToModule($url, $controller, $depr = '/') { $array = explode($depr, $url, 2); $action = !empty($array[0]) ? $array[0] : Config::get('default_action'); if (!empty($array[1])) { self::parseUrlParams($array[1]); } return ['type' => 'module', 'module' => $controller . '/' . $action]; } ~~~ ### Route::bindToClass() ~~~ public static function bindToClass($url, $class, $depr = '/') { $array = explode($depr, $url, 2); $action = !empty($array[0]) ? $array[0] : Config::get('default_action'); if (!empty($array[1])) { self::parseUrlParams($array[1]); } return ['type' => 'method', 'method' => [$class, $action]]; } ~~~ ### Route::bindToCOntroller() ~~~ public static function bindToController($url, $controller, $depr = '/') { $array = explode($depr, $url, 2); $action = !empty($array[0]) ? $array[0] : Config::get('default_action'); if (!empty($array[1])) { self::parseUrlParams($array[1]); } return ['type' => 'controller', 'controller' => $controller . '/' . $action]; } ~~~ ## 4-4 路由快捷注册 >>路由快捷注册包括快捷接口(Route::controller)和请求类型的前缀注册(Route::setMethodPrefix) ### Route::controller() ~~~ public static function controller($rule, $route = '', $option = [], $pattern = []) { foreach (self::$methodPrefix as $type => $val) { self::$type($rule . '/:action', $route . '/' . $val . ':action', $option, $pattern); } } ~~~ ### Route::setMethodPrefix() >>快捷路由的方法前缀默认为 ~~~ private static $methodPrefix = [ 'GET' => 'get', 'POST' => 'post', 'PUT' => 'put', 'DELETE' => 'delete', ]; ~~~ >可以使用Route::setMethodPrefix()重定义快捷路由方法前缀 ~~~ public static function setMethodPrefix($method, $prefix = '') { if (is_array($method)) { self::$methodPrefix = array_merge(self::$methodPrefix, array_change_key_case($method, CASE_UPPER)); } else { self::$methodPrefix[strtoupper($method)] = $prefix; } } ~~~ ## 4-5 路由变量规则 >>Route::pattern()注册和获取变量正则规则 ### Route::pattern() ~~~ public static function pattern($name = null, $rule = '') { if (is_array($name)) { self::$rules['pattern'] = array_merge(self::$rules['pattern'], $name); } else { self::$rules['pattern'][$name] = $rule; } } ~~~ ## 4-6 rest方法格式修改 >>Route::rest()修改rest默认的规则格式 >默认的rest的规则格式为 ~~~ private static $rest = [ 'index' => ['GET', '', 'index'], 'create' => ['GET', '/create', 'create'], 'edit' => ['GET', '/:id/edit', 'edit'], 'read' => ['GET', '/:id', 'read'], 'save' => ['POST', '', 'save'], 'update' => ['PUT', '/:id', 'update'], 'delete' => ['DELETE', '/:id', 'delete'], ]; ~~~ >可以使用Route::rest()方法重定义rest方法格式 ### Route::rest() ~~~ public static function rest($name, $resource = []) { if (is_array($name)) { self::$rest = array_merge(self::$rest, $name); } else { self::$rest[$name] = $resource; } } ~~~ ## 4-7 路由别名注册 >>Route::alias()可以注册路由的别名 ### Route::alias() ~~~ public static function alias($rule = null, $route = '', $option = []) { if (is_array($rule)) { self::$rules['alias'] = array_merge(self::$rules['alias'], $rule); } else { self::$rules['alias'][$rule] = $option ? [$route, $option] : $route; } } ~~~ #5 路由解析 >>路由解析 根据Url信息查找获取对应的应用地址。 >按照查找的层次分为以下 >Url有效性检测 >Url对应路由规则查找 >Url参数解析 ## 5-1 Url有效性检测 >>Url有效性检测,包括以下 >Url检测入口Route::check() >路由别名检测Route::checkRouteAlias() >Url域名检测Route::checkDomain() >Url绑定检测Route::checkBind() ### Route::check() ~~~ public static function check($request, $url, $depr = '/', $checkDomain = false) { // 分隔符替换 确保路由定义使用统一的分隔符 if ('/' != $depr) { $url = str_replace($depr, '/', $url); } if (strpos($url, '/') && isset(self::$rules['alias'][strstr($url, '/', true)])) { // 检测路由别名 $result = self::checkRouteAlias($request, $url, $depr); if (false !== $result) { return $result; } } $method = $request->method(); // 获取当前请求类型的路由规则 $rules = self::$rules[$method]; // 检测域名部署 if ($checkDomain) { self::checkDomain($request, $rules, $method); } // 检测URL绑定 $return = self::checkUrlBind($url, $rules, $depr); if (false !== $return) { return $return; } if ('/' != $url) { $url = rtrim($url, '/'); } if (isset($rules[$url])) { // 静态路由规则检测 $rule = $rules[$url]; if (true === $rule) { $rule = self::getRouteExpress($url); } if (!empty($rule['route'])) { return self::parseRule($url, $rule['route'], $url, $rule['option']); } } // 路由规则检测 if (!empty($rules)) { return self::checkRoute($request, $rules, $url, $depr); } return false; } ~~~ ### Route::checkRouteAlias() >>路由别名检测checkRouteAlias()中 >首先获取别名对应的路由规则 >然后检查参数的有效性Route::checkOption() >最后进行Url格式中绑定类型的检测 ~~~ private static function checkRouteAlias($request, $url, $depr) { $array = explode('/', $url, 2); $item = self::$rules['alias'][$array[0]]; if (is_array($item)) { list($rule, $option) = $item; } else { $rule = $item; } // 参数有效性检查 if (isset($option) && !self::checkOption($option, $url, $request)) { // 路由不匹配 return false; } elseif (0 === strpos($rule, '\\')) { // 路由到类 return self::bindToClass($array[1], substr($rule, 1), $depr); } elseif (0 === strpos($url, '@')) { // 路由到控制器类 return self::bindToController($array[1], substr($rule, 1), $depr); } else { // 路由到模块/控制器 return self::bindToModule($array[1], $rule, $depr); } } ~~~ ### Route::checkDomain() >>域名规则检测checkDomain()中 >首先获取网络请求域名(host)对应的注册的域名规则(rules['domain]) >然后将url相关参数拼接到新的域名规则url中 >最后进行绑定类型的检测与转换 ~~~ public static function checkDomain($request, &$currentRules, $method = 'GET') { // 域名规则 $rules = self::$rules['domain']; // 开启子域名部署 支持二级和三级域名 if (!empty($rules)) { $host = $request->host(); if (isset($rules[$host])) { // 完整域名或者IP配置 $item = $rules[$host]; } else { $rootDomain = Config::get('url_domain_root'); if ($rootDomain) { // 配置域名根 例如 thinkphp.cn 163.com.cn 如果是国家级域名 com.cn net.cn 之类的域名需要配置 $domain = explode('.', rtrim(stristr($host, $rootDomain, true), '.')); } else { $domain = explode('.', $host, -2); } // 子域名配置 if (!empty($domain)) { // 当前子域名 $subDomain = implode('.', $domain); self::$subDomain = $subDomain; $domain2 = array_pop($domain); if ($domain) { // 存在三级域名 $domain3 = array_pop($domain); } if ($subDomain && isset($rules[$subDomain])) { // 子域名配置 $item = $rules[$subDomain]; } elseif (isset($rules['*.' . $domain2]) && !empty($domain3)) { // 泛三级域名 $item = $rules['*.' . $domain2]; $panDomain = $domain3; } elseif (isset($rules['*']) && !empty($domain2)) { // 泛二级域名 if ('www' != $domain2) { $item = $rules['*']; $panDomain = $domain2; } } } } if (!empty($item)) { if (isset($item['[bind]'])) { // 解析子域名部署规则 list($rule, $option, $pattern) = $item['[bind]']; if (!empty($option['https']) && !$request->isSsl()) { // https检测 throw new HttpException(404, 'must use https request:' . $host); } if (strpos($rule, '?')) { // 传入其它参数 $array = parse_url($rule); $result = $array['path']; parse_str($array['query'], $params); if (isset($panDomain)) { $pos = array_search('*', $params); if (false !== $pos) { // 泛域名作为参数 $params[$pos] = $panDomain; } } $_GET = array_merge($_GET, $params); } else { $result = $rule; } if (0 === strpos($result, '\\')) { // 绑定到命名空间 例如 \app\index\behavior self::$bind = ['type' => 'namespace', 'namespace' => $result]; } elseif (0 === strpos($result, '@')) { // 绑定到类 例如 @app\index\controller\User self::$bind = ['type' => 'class', 'class' => substr($result, 1)]; } else { // 绑定到模块/控制器 例如 index/user self::$bind = ['type' => 'module', 'module' => $result]; } self::$domainBind = true; } else { self::$domainRule = $item; $currentRules = isset($item[$method]) ? $item[$method] : $item['*']; } } } } ~~~ ### Route::checkUrlBind() >>Url绑定检测checkUrlBind()中 >首先获取绑定类型 >然后根据绑定类型解析为不同的绑定规则 ~~~ private static function checkUrlBind(&$url, &$rules, $depr = '/') { if (!empty(self::$bind)) { $type = self::$bind['type']; $bind = self::$bind[$type]; // 记录绑定信息 App::$debug && Log::record('[ BIND ] ' . var_export($bind, true), 'info'); // 如果有URL绑定 则进行绑定检测 switch ($type) { case 'class': // 绑定到类 return self::bindToClass($url, $bind, $depr); case 'namespace': // 绑定到命名空间 return self::bindToNamespace($url, $bind, $depr); case 'module': // 如果有模块/控制器绑定 针对路由到 模块/控制器 有效 $url = (empty(self::$domainBind) ? $bind . '/' : '') . ltrim($url, '/'); break; } } return false; } ~~~ ## 5-2 Url路由规则查找 >>Url路由规则查找包括静态路由查找和非静态路由查找 >静态路由检测Route::getRouteExpress() >Url规则解析Route::parseRule() >路由规则检测Route::checkRoute() ### Route::getRouteExpress() >>静态路由检测 url直接对应的路由规则 >首先获取注册的静态路由规则 >然后调用parseRule()解析路由规则 ~~~ private static function getRouteExpress($key) { return self::$domainRule ? self::$domainRule['*'][$key] : self::$rules['*'][$key]; } ~~~ ### Route::parseRule() >>路由规则解析parseRule() >首先解析路由规则的url参数信息 >然后解析路由规则的对应Option选项参数到路由地址 >检测是否绑定到模型 >然后合并Url的额外参数 >记录路由信息到网络请求 >执行路由检查的后调after_behavior钩子 >最后根据地址route的不同类型组装不同类型的应用路由 ~~~ private static function parseRule($rule, $route, $pathinfo, $option = [], $matches = [], $merge = false) { // 解析路由规则变量 if ($rule) { $rule = explode('/', $rule); // 获取URL地址中的参数 $paths = $merge ? explode('/', $pathinfo, count($rule)) : explode('/', $pathinfo); foreach ($rule as $item) { $fun = ''; if (0 === strpos($item, '[:')) { $item = substr($item, 1, -1); } if (0 === strpos($item, ':')) { $var = substr($item, 1); $matches[$var] = array_shift($paths); } else { // 过滤URL中的静态变量 array_shift($paths); } } } else { $paths = explode('/', $pathinfo); } // 获取路由地址规则 if (is_string($route) && isset($option['prefix'])) { // 路由地址前缀 $route = $option['prefix'] . $route; } // 替换路由地址中的变量 if (is_string($route) && !empty($matches)) { foreach ($matches as $key => $val) { if (false !== strpos($route, ':' . $key)) { $route = str_replace(':' . $key, $val, $route); unset($matches[$key]); } } } // 绑定模型数据 if (isset($option['bind_model'])) { $bind = []; foreach ($option['bind_model'] as $key => $val) { if ($val instanceof \Closure) { $result = call_user_func_array($val, [$matches]); } else { if (is_array($val)) { $fields = explode('&', $val[1]); $model = $val[0]; $exception = isset($val[2]) ? $val[2] : true; } else { $fields = ['id']; $model = $val; $exception = true; } $where = []; $match = true; foreach ($fields as $field) { if (!isset($matches[$field])) { $match = false; break; } else { $where[$field] = $matches[$field]; } } if ($match) { $query = strpos($model, '\\') ? $model::where($where) : Loader::model($model)->where($where); $result = $query->failException($exception)->find(); } } if (!empty($result)) { $bind[$key] = $result; } } Request::instance()->bind($bind); } // 解析额外参数 self::parseUrlParams(empty($paths) ? '' : implode('/', $paths), $matches); // 记录匹配的路由信息 Request::instance()->routeInfo(['rule' => $rule, 'route' => $route, 'option' => $option, 'var' => $matches]); // 检测路由after行为 if (!empty($option['after_behavior'])) { if ($option['after_behavior'] instanceof \Closure) { $result = call_user_func_array($option['after_behavior'], []); } else { foreach ((array) $option['after_behavior'] as $behavior) { $result = Hook::exec($behavior, ''); if (!is_null($result)) { break; } } } // 路由规则重定向 if ($result instanceof Response) { return ['type' => 'response', 'response' => $result]; } elseif (is_array($result)) { return $result; } } if ($route instanceof \Closure) { // 执行闭包 $result = ['type' => 'function', 'function' => $route]; } elseif (0 === strpos($route, '/') || 0 === strpos($route, 'http')) { // 路由到重定向地址 $result = ['type' => 'redirect', 'url' => $route, 'status' => isset($option['status']) ? $option['status'] : 301]; } elseif (0 === strpos($route, '\\')) { // 路由到方法 $method = strpos($route, '@') ? explode('@', $route) : $route; $result = ['type' => 'method', 'method' => $method]; } elseif (0 === strpos($route, '@')) { // 路由到控制器 $result = ['type' => 'controller', 'controller' => substr($route, 1)]; } else { // 路由到模块/控制器/操作 $result = self::parseModule($route); } return $result; } ~~~ ### Route::checkRoute() >>如果Url直接对应的路由规则为空。 >则进行miss和auto路由检测 ~~~ private static function checkRoute($request, $rules, $url, $depr = '/', $group = '', $options = []) { foreach ($rules as $key => $item) { if (true === $item) { $item = self::getRouteExpress($key); } if (!isset($item['rule'])) { continue; } $rule = $item['rule']; $route = $item['route']; $vars = $item['var']; $option = $item['option']; $pattern = $item['pattern']; // 检查参数有效性 if (!self::checkOption($option, $url, $request)) { continue; } if (isset($option['ext'])) { // 路由ext参数 优先于系统配置的URL伪静态后缀参数 $url = preg_replace('/\.' . $request->ext() . '$/i', '', $url); } if (is_array($rule)) { // 分组路由 $pos = strpos(str_replace('<', ':', $key), ':'); if (false !== $pos) { $str = substr($key, 0, $pos); } else { $str = $key; } if (is_string($str) && $str && 0 !== strpos($url, $str)) { continue; } $result = self::checkRoute($request, $rule, $url, $depr, $key, $option); if (false !== $result) { return $result; } } elseif ($route) { if ('__miss__' == $rule || '__auto__' == $rule) { // 指定特殊路由 $var = trim($rule, '__'); ${$var} = $item; continue; } if ($group) { $rule = $group . ($rule ? '/' . ltrim($rule, '/') : ''); } if (isset($options['bind_model']) && isset($option['bind_model'])) { $option['bind_model'] = array_merge($options['bind_model'], $option['bind_model']); } $result = self::checkRule($rule, $route, $url, $pattern, $option); if (false !== $result) { return $result; } } } if (isset($auto)) { // 自动解析URL地址 return self::parseUrl($auto['route'] . '/' . $url, $depr); } elseif (isset($miss)) { // 未匹配所有路由的路由规则处理 return self::parseRule('', $miss['route'], $url, $miss['option']); } return false; } ~~~ ## 5-3 Url参数解析 >>Url参数解析是在路由解析过程中调用的子过程,包括以下 >Url解析入口 >UrlPath解析 >Url参数解析 >Module解析 ### Route::parseUrl() ~~~ public static function parseUrl($url, $depr = '/', $autoSearch = false) { if (isset(self::$bind['module'])) { // 如果有模块/控制器绑定 $url = self::$bind['module'] . '/' . ltrim($url, '/'); } list($path, $var) = self::parseUrlPath($url, $depr); $route = [null, null, null]; if (isset($path)) { // 解析模块 $module = Config::get('app_multi_module') ? array_shift($path) : null; if ($autoSearch) { // 自动搜索控制器 $dir = APP_PATH . ($module ? $module . DS : '') . 'controller'; $suffix = App::$suffix || Config::get('controller_suffix') ? ucfirst(Config::get('url_controller_layer')) : ''; $item = []; foreach ($path as $val) { $item[] = array_shift($path); if (is_file($dir . DS . $val . $suffix . EXT)) { break; } else { $dir .= DS . $val; } } $controller = implode('.', $item); } else { // 解析控制器 $controller = !empty($path) ? array_shift($path) : null; } // 解析操作 $action = !empty($path) ? array_shift($path) : null; // 解析额外参数 self::parseUrlParams(empty($path) ? '' : implode('/', $path)); // 封装路由 $route = [$module, $controller, $action]; if (isset(self::$rules['name'][implode($depr, $route)])) { throw new HttpException(404, 'invalid request:' . $url); } } return ['type' => 'module', 'module' => $route]; } ~~~ ### Route::parseUrlPath() ~~~ private static function parseUrlPath($url, $depr = '/') { // 分隔符替换 确保路由定义使用统一的分隔符 if ('/' != $depr) { $url = str_replace($depr, '/', $url); } $url = trim($url, '/'); $var = []; if (false !== strpos($url, '?')) { // [模块/控制器/操作?]参数1=值1&参数2=值2... $info = parse_url($url); $path = explode('/', $info['path']); parse_str($info['query'], $var); } elseif (strpos($url, '/')) { // [模块/控制器/操作] $path = explode('/', $url); } elseif (false !== strpos($url, '=')) { // 参数1=值1&参数2=值2... parse_str($url, $var); } else { $path = [$url]; } return [$path, $var]; } ~~~ ### Route::parseUrlParams() ~~~ private static function parseUrlParams($url, &$var = []) { if ($url) { if (Config::get('url_param_type')) { $var += explode('/', $url); } else { preg_replace_callback('/(\w+)\/([^\/]+)/', function ($match) use (&$var) { $var[$match[1]] = strip_tags($match[2]); }, $url); } } // 设置当前请求的参数 Request::instance()->route($var); } ~~~ ### Route::parseModule() >>在模块/控制/操作类型的应用中调用parseModule() >解析url到对应的类型应用 ~~~ private static function parseModule($url, $depr = '/') { list($path, $var) = self::parseUrlPath($url, $depr); $action = array_pop($path); $controller = !empty($path) ? array_pop($path) : null; $module = Config::get('app_multi_module') && !empty($path) ? array_pop($path) : null; $method = Request::instance()->method(); if (Config::get('use_action_prefix') && !empty(self::$methodPrefix[$method])) { // 操作方法前缀支持 $action = 0 !== strpos($action, self::$methodPrefix[$method]) ? self::$methodPrefix[$method] . $action : $action; } // 设置当前请求的路由变量 Request::instance()->route($var); // 路由到模块/控制器/操作 return ['type' => 'module', 'module' => [$module, $controller, $action], 'convert' => false]; } ~~~ ### Route::parseVar() >>parseVar()解析规则的变量信息 >默认的变量规则为?,[:,:三种 >也可以注册变量规则 ~~~ private static function parseVar($rule) { // 提取路由规则中的变量 $var = []; foreach (explode('/', $rule) as $val) { $optional = false; if (false !== strpos($val, '<') && preg_match_all('/<(\w+(\??))>/', $val, $matches)) { foreach ($matches[1] as $name) { if (strpos($name, '?')) { $name = substr($name, 0, -1); $optional = true; } else { $optional = false; } $var[$name] = $optional ? 2 : 1; } } if (0 === strpos($val, '[:')) { // 可选参数 $optional = true; $val = substr($val, 1, -1); } if (0 === strpos($val, ':')) { // URL变量 $name = substr($val, 1); $var[$name] = $optional ? 2 : 1; } } return $var; } ~~~