php编写一个简单的路由类
程序员文章站
2022-05-14 13:22:00
类代码:复制代码 代码如下:
类代码:
<?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 )
{
// 第一种类型以/分隔
$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';
}
// 去除空项
foreach ($temp as $val)
{
if ($val)
{
$url[] = $val;
}
}
list($controller, $operate) = $url;
//有参数的情况
$params = array();
if ( count($url)>2 )
{
array_shift($url);
array_shift($url);
$params = $url;
}
return
array(
"controller" => $controller,
"operate" => $operate,
"params" => $params,
);
}
}
?>
调用方法:
<?php
$url = new router();
$url->getrouter(1);
print_r($url); //在这里可以看到各元素
?>
复制代码 代码如下:
<?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 )
{
// 第一种类型以/分隔
$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';
}
// 去除空项
foreach ($temp as $val)
{
if ($val)
{
$url[] = $val;
}
}
list($controller, $operate) = $url;
//有参数的情况
$params = array();
if ( count($url)>2 )
{
array_shift($url);
array_shift($url);
$params = $url;
}
return
array(
"controller" => $controller,
"operate" => $operate,
"params" => $params,
);
}
}
?>
调用方法:
复制代码 代码如下:
<?php
$url = new router();
$url->getrouter(1);
print_r($url); //在这里可以看到各元素
?>
上一篇: PHP与C#分别格式化文件大小的代码
下一篇: web前端性能优化