PHP writes a simple routing class

  • 2020-03-31 21:37:57
  • OfStack

Class code:
 
<?php 
class Router 
{ 
public function getRouter($types = 1) 
{ 
if ( isset($_SERVER['PATH_INFO']) ) 
{ 
$query_string = substr(str_replace(array('.html','.htm', '.asp', '//'), '',$_SERVER['PATH_INFO']),1); 
} 
else 
{ 
$query_string = str_replace($_SERVER['SCRIPT_NAME'], '',$_SERVER['PHP_SELF']); 
} 
if ( $types == 1 ) 
{ 
//The first type is separated by /
$temp = explode('/', $query_string); 
} 
elseif ($types == 2) 
{ 
$temp = explode('-', $query_string); 
} 
elseif ($types == 3) 
{ 
return array('Controller'=>$_GET['controller']); 
} 
if ( empty($temp[0]) ) 
{ 
return array('Controller' => 'index','Operate' => 'index'); 
} 
if ( empty($temp[1]) ) 
{ 
$temp[] = 'index'; 
} 
//Remove empty
foreach ($temp as $val) 
{ 
if ($val) 
{ 
$url[] = $val; 
} 
} 
list($controller, $operate) = $url; 
//In the case of parameters
$params = array(); 
if ( count($url)>2 ) 
{ 
array_shift($url); 
array_shift($url); 
$params = $url; 
} 
return 
array( 
"Controller" => $controller, 
"Operate" => $operate, 
"params" => $params, 
); 
} 
} 
?> 

Call method:

<?php 
$url = new Router(); 
$url->getRouter(1); 
print_r($url); //You can see the elements here
?> 

Related articles: