thinkphp routing rules implement of apache rewriting using sample details and pseudo static functionality

  • 2021-01-11 01:56:05
  • OfStack


<?php 
//thinkphp  Routing definition rules   
$route = array(
  'news/:action/:year\d/:month/:day'=>'news/read?year=:2&month=:3&day=:4',
    'news/:action^delete|update|insert/:year\d/:month/:day'=>array(                'news/read?extra=:2&status=1','year=:2&month=:3&day=:4'),
     );
$url  = 'http://www.test.com/index.php/news/read/2012/2/21/extraparam/test.html';
 
// suffix 
$extension = 'html';
// known : $_SERVER['PATH_INFO'] = 'news/read/2012/2/21/extraparam/test.html';
$regx = 'news/read/2012/2/21/extraparam/test.html';
// Loop matches routing rules 
foreach($route as $key=>$value){
  // If the match is successful, the match is not continued 
  if(parseUrlRule($key,$value,$regx,$extension))
   break;
}
// Running results:   print $_GET
//Array
//  (
//      [actionName] => read
//      [moduleName] => news
//      [extra] => 2012
//      [status] => 1
//      [extraparam] => test
//      [year] => 2012
//      [month] => 2
//      [day] => 21
//      [finalUrl] => news/read?extra=2012&status=1&extraparam=test&year=2012&month=2&day=21
//  )
//  [Finished in 0.6s]
// Equivalent access : http://www.test.com/news/read?extra=2012&status=1&extraparam=test&year=2012&month=2&day=21
// It's going to be deployed index.php Hide, open apache Rewriting module of 
// Rewrite rules   :  RewriteRule  ^(.+)$  /index.php/$1 
// After opening, apache Will automatically  http:/www.test.com/news/read/2012/2/21/extraparam/test.html convert  http:/www.test.com/index.php/news/read/2012/2/21/extraparam/test.html
/**
 *  @$rule  string     Routing rules    
 *  @$route string     The new address of the rule map 
 *  @$regx  string     The address bar pathinfo string 
 *  @$extension stirng   Pseudo static extension name 
 *  return  bool 
 */
function parseUrlRule($rule,$route,$regx,$extension=null){
   // Remove the suffix name 
   !is_null($extension) && $regx = str_replace('.'.$extension,'',$regx);
   // Put routing rules and addresses together , Split it into an array, and then match it item by item 
   $ruleArr = explode('/',$rule);
   $regxArr = explode('/',$regx);
   //$route Passed as an array, takes the first 1 a 
   $url = is_array($route) ? $route[0] : $route;
   $match =true;
   // Matching detection 
   foreach($ruleArr as $key=>$value){
     if(strpos($value,':')===0){
      if(substr($value,-2)=='\\d' && !is_numeric($regxArr[$key])){
       $match = false;
       break;
      }elseif(strpos($value,'^')){
       $stripArr = explode('|',trim(strstr($value,'^'),'^'));
       if(in_array($regxArr[$key],$stripArr)){
        $match = false;
        break;
       }
      }
     // Static items are not case sensitive 
     }elseif(strcasecmp($value, $regxArr[$key])!==0) {
      $match = false;
      break;
     }
   }
   // The match is successful 
   if($match){
     // Writes a dynamic variable to an array $matches  , while removing the static match 
     foreach($ruleArr as $key=>$value){
       if(strpos($value,':')===0){
        // Gets dynamic variables as array subscripts 
        if(substr($value,-2,1)=='\\')
         $matchKey = substr($value,1,-2);
        elseif($pos=strpos($value,'^'))
         $matchKey =substr($value,1,$pos-1); 
        else
         $matchKey = substr($value,1);
        $matches[$matchKey] = array_shift($regxArr);
       }else
        array_shift($regxArr);   // Removes static matches 
     }

     // Gets a value in an array for substitution with a subpattern 
     $values = array_values($matches);
     // Regular matching replacement , You need to use the 'e' As a modifier 
     $url = preg_replace('/:(\d+)/e','$values[\\1-1]',$url);
     // parsing url     format :   grouping / The module / operation ?key1=value1&key2=value2
     if(strpos($url,'?')!==false){   
       //  grouping / The module / operation ?key1=value1&key2=value2
       $arr = parse_url($url);
       $paths = explode('/',$arr['path']);
       parse_str($arr['query'],$queryArr);
     }elseif(strpos($url,'/')!==false)  // grouping / The module / operation )
       $paths = explode('/',$url);
     else        // key1=value1&key2=value2
       parse_str($url,$queryArr);

     // To obtain   grouping   The module   operation 
     if(!empty($paths)){
       $var['actionName'] = array_pop($paths);
       $var['moduleName'] = array_pop($paths);
       if(!empty($paths)){
        $groupList = 'Home,Admin';
        $temp = array_pop($paths);
        if(in_array($temp,explode(',',$groupList)))
         $var['groupName'] = $temp;
       }
     }
     // Merged to GET Array for easy global call 
     $_GET = array_merge($_GET,$var);
     // Consolidation parameters 
     if(isset($queryArr))
      $_GET = array_merge($_GET,$queryArr);
     // matching url The remaining parameters in the 
     preg_replace('/(\w+)\/([^,\/]+)/e','$tempArr[\'\\1\']=\'\\2\'',implode('/',$regxArr));
     if(!empty($tempArr))
      $_GET = array_merge($_GET,$tempArr);

     //route If it's an array 
     if(is_array($route)){
       $route[1]=preg_replace('/:(\d+)/e','$values[\\1-1]',$route[1]);
       parse_str($route[1],$var);
       $_GET = array_merge($_GET,$var);
       strpos($url,'?')!==false ? $der ='&' : $der='?';
       // Finally write to $_GET Parameters, including 3 A part of 
       //1. Address bar remaining parameters 
       //2. Parameters in the route address 
       //3.$route It's the first in an array 2 A parameter 
       if(!empty($tempArr))
        $var = array_merge($tempArr,$var);
       $url .=$der.http_build_query($var);
     }
     $_GET['finalUrl'] = $url;
     // ensure $_REQUEST  Can also access 
     $_REQUEST = array_merge($_REQUEST,$_GET);
     // The results of 
     print_r($_GET);
     return true;
   }
   return $match;
}

// Here is the regular routing code:  
$rule = '/news\/read\/(\d+)\/(\d+)\/(\d+)/';
$route ='news/read?year=:1&month=:2&day=:3';
$regx = 'news/read/2012/2/21/extraparam/test.html';
$extension = 'html';
parseUrlRuleRegx($rule,$route,$regx,$extension);

/**
 *  @$rule  string     Routing rules    
 *  @$route string     The new address of the rule map 
 *  @$regx  string     The address bar pathinfo string 
 *  @$extension stirng   Pseudo static extension name 
 *  return  bool 
 */
function parseUrlRuleRegx($rule,$route,$regx,$extension=null){
   !is_null($extension) && $regx = str_replace('.'.$extension,'',$regx);
   $url = is_array($route) ? $route[0] : $route;
   if(preg_match($rule,$regx,$matches)){
     $url = preg_replace('/:(\d+)/e','$matches[\\1]',$url);
   }else
       return false;
   // parsing url     format :   grouping / The module / operation ?key1=value1&key2=value2
   if(strpos($url,'?')!==false){   
     //  grouping / The module / operation ?key1=value1&key2=value2
     $arr = parse_url($url);
     $paths = explode('/',$arr['path']);
     parse_str($arr['query'],$queryArr);
   }elseif(strpos($url,'/')!==false)  // grouping / The module / operation )
     $paths = explode('/',$url);
   else        // key1=value1&key2=value2
     parse_str($url,$queryArr);

   // To obtain   grouping   The module   operation 
   if(!empty($paths)){
     $var['actionName'] = array_pop($paths);
     $var['moduleName'] = array_pop($paths);
     if(!empty($paths)){
      $groupList = 'Home,Admin';
      $temp = array_pop($paths);
      if(in_array($temp,explode(',',$groupList)))
       $var['groupName'] = $temp;
     }
   }
   // Merged to GET Array for easy global call 
   $_GET = array_merge($_GET,$var);
   if(isset($queryArr))
    $_GET = array_merge($_GET,$queryArr);
   // Matches the remaining parameters 
   $regx = str_replace($matches[0],'',$regx);
   preg_replace('/(\w+)\/([^,\/]+)/e','$tempArr[\'\\1\']=\'\\2\'',$regx);
   if(!empty($tempArr)){
    $_GET = array_merge($_GET,$tempArr);
    strpos($url,'?')!==false ? $der='&':$der='?';
    $url .=$der.http_build_query($tempArr);
   }
   if(is_array($route)){
     $route[1] = preg_replace('/:(\d+)/e','$matches[\\1]',$route[1]);
     parse_str($route[1],$var);
     if(!empty($var)){
      !empty($queryArr) && $var =array_merge($queryArr,$var);
      $_GET= array_merge($_GET,$var);
     }
     strpos($url,'?')!==false ? $der='&':$der='?';
     $url .=$der.http_build_query($var);
   }
 
   $_GET['finalUrl'] = $url;
   print_r($_GET);
   $_REQUEST = array_merge($_GET,$_REQUEST);
   return true;
}
// Running results:  
//Array
// (
//     [actionName] => read
//     [moduleName] => news
//     [year] => 2012
//     [month] => 2
//     [day] => 21
//     [extraparam] => test
//     [finalUrl] => news/read?year=2012&month=2&day=21&extraparam=test
// )
// [Finished in 0.1s]


Related articles: