这篇文章将为大家详细讲解有关PHP中如何实现路由类,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
在core目录下,新建一个名为lib的子目录,然后把我们前面写个route.php这个文件移动到这个目录下。

因为route类文件路径修改,所以在实例化的时候:
new \core\lib\route();
然后我们来完善route.php:
<?php
namespace core\lib;
class Route
{
public $controller; // 控制器
public $action; // 方法(动作)
public function __construct()
{
// xxx.com/index.php/index/index
// xxx.com/index.php/index
/*
* 1.隐藏index.php
* 2.获取URL 参数部分
* 3.返回对应控制器和方法
* */
if(isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] != '/'){
// 处理成这种格式:index/index
$path = $_SERVER['REQUEST_URI'];
$pathArr = explode('/',trim($path,'/'));
if(isset($pathArr[0])){
$this->controller = $pathArr[0];
}
unset($pathArr[0]);
if(isset($pathArr[1])){
$this->action = $pathArr[1];
unset($pathArr[1]);
}else{
$this->action = 'index';
}
// url多余部分(参数部分)转换成 GET
// id/1/str/2
$count = count($pathArr) + 2;
$i = 2;
while($i < $count){
if(isset($pathArr[$i + 1])){
$_GET[$pathArr[$i]] == $pathArr[$i + 1];
}
$i = $i + 2;
}
p($_GET); // 打印GET
}else{
$this->controller = 'index'; // 默认控制器
$this->action = 'index'; // 默认方法
}
}
}
关于“PHP中如何实现路由类”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。