本文實例講述了PHP從零開始打造自己的MVC框架之路由類實現方法。分享給大家供大家參考,具體如下:
在core目錄下,新建一個名為lib的子目錄,然后把我們前面寫個route.php這個文件移動到這個目錄下。

因為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相關內容感興趣的讀者可查看本站專題:《php面向對象程序設計入門教程》、《PHP數組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結》、《php字符串(string)用法總結》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。
您可能感興趣的文章:- PHP從零開始打造自己的MVC框架之類的自動加載實現方法詳解
- PHP命名空間和自動加載類
- PHP動態地創建屬性和方法, 對象的復制, 對象的比較,加載指定的文件,自動加載類文件,命名空間
- PHP實現的簡單路由和類自動加載功能
- PHP命名空間與自動加載類詳解
- 解析php類的注冊與自動加載
- php類自動加載器實現方法
- PHP類的自動加載機制實現方法分析
- php項目中類的自動加載實例講解
- PHP MVC框架中類的自動加載機制實例分析