## 2.3 路由類
~~~
1. 調整目錄結構
2. 路由類的作用
~~~
### 1. 調整目錄結構
把 `route.php` 這些類放在 `/core/lib` 中。
文件:`D:\wamp\www\web.com\core\route.php` 放在 `D:\wamp\www\web.com\core\lib\route.php`
因此:我們的**命名空間也將發生變化**,一下兩處修改了命名空間。
*D:\wamp\www\web.com\core\lib\route.php*
~~~
<?php
namespace core\lib;
class route
{
public function __construct()
{
echo "路由初始化成功";
}
}
~~~
*D:\wamp\www\web.com\index.php*
~~~
// 實現自動加載
spl_autoload_register('\core\thinkphp::load');
~~~
### 2. 路由類的作用
以訪問地址`xxx.com/index.php/index/index` 為例。
1. 隱藏index.php,變為:`xxx.com/index/index`
2. 返回對應的控制器、方法,默認為`index`
3. 獲取URL參數的部分,帶參數的地址:`xxx.com/index/index/id/3`
#### 2.1 去除index.php
這里以Apache服務器為例。
在根目錄下添加文件:`D:\wamp\www\web.com\.htaccess`
~~~
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
</IfModule>
~~~
#### 2.2 使用超全局變量 `$_SERVER['REQUEST_URI']`
查看 `$_SERVER['REQUEST_URI']` 的值。

*D:\wamp\www\web.com\core\lib\route.php*
~~~
<?php
namespace core\lib;
class route
{
public $ctrl;
public $action;
public function __construct()
{
/**
* xxx.com/index.php/index/index
* 1. 隱藏index.php
* 2. 返回對應的控制器、方法
* 3. 獲取URL參數的部分
*/
if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] != '/' ) {
$path = $_SERVER['REQUEST_URI'];
$pathArr = explode('/', trim($path, '/'));
if (isset($pathArr[0])) {
$this->ctrl = $pathArr[0];
}
unset($pathArr[0]);
if (isset($pathArr[1])) {
$this->action = $pathArr[1];
unset($pathArr[1]);
} else{
$this->action = 'index';
}
// 把剩余的參數信息,寫入$_GET
$count = count($pathArr) + 2;
$i = 2;
while ($i < $count) {
if (isset($pathArr[$i + 1])) {
$_GET[$pathArr[$i]] = $pathArr[$i + 1];
}
$i += 2;
}
} else{
$this->ctrl = 'index';
$this->action = 'index';
}
}
}
~~~
#### 2.3 查看效果
在 *D:\wamp\www\web.com\core\thinkphp.php*
~~~
static public function run()
{
$route = new \core\lib\route();
// 打印路由對象
p($route);
}
~~~

打印存儲的參數信息如下:
