欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php编写一个简单的路由类_PHP教程

程序员文章站 2022-05-30 09:46:09
...
类代码:
复制代码 代码如下:

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,
);
}
}
?>

调用方法:
复制代码 代码如下:

$url = new Router();
$url->getRouter(1);
print_r($url); //在这里可以看到各元素
?>

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/323174.htmlTechArticle类代码: 复制代码 代码如下: ?php class Router { public function getRouter($types = 1) { if ( isset($_SERVER['PATH_INFO']) ) { $query_string = substr(str_replace(array('....