本文實(shí)例講述了PHP從零開始打造自己的MVC框架之路由類實(shí)現(xiàn)方法。分享給大家供大家參考,具體如下:
在core目錄下,新建一個名為lib的子目錄,然后把我們前面寫個route.php這個文件移動到這個目錄下。
![](http://img.jbzj.com/file_images/article/201906/20196394100466.png?20195394313)
因?yàn)閞oute類文件路徑修改,所以在實(shí)例化的時候:
然后我們來完善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 參數(shù)部分
* 3.返回對應(yīng)控制器和方法
* */
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多余部分(參數(shù)部分)轉(zhuǎn)換成 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'; // 默認(rèn)控制器
$this->action = 'index'; // 默認(rèn)方法
}
}
}
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計有所幫助。
您可能感興趣的文章:- PHP從零開始打造自己的MVC框架之類的自動加載實(shí)現(xiàn)方法詳解
- PHP命名空間和自動加載類
- PHP動態(tài)地創(chuàng)建屬性和方法, 對象的復(fù)制, 對象的比較,加載指定的文件,自動加載類文件,命名空間
- PHP實(shí)現(xiàn)的簡單路由和類自動加載功能
- PHP命名空間與自動加載類詳解
- 解析php類的注冊與自動加載
- php類自動加載器實(shí)現(xiàn)方法
- PHP類的自動加載機(jī)制實(shí)現(xiàn)方法分析
- php項目中類的自動加載實(shí)例講解
- PHP MVC框架中類的自動加載機(jī)制實(shí)例分析