欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP MVC框架路由學(xué)習(xí)筆記

 更新時間:2016年03月02日 11:11:51   投稿:mrr  
這篇文章主要介紹了PHP MVC框架路由學(xué)習(xí)筆記的相關(guān)資料,需要的朋友可以參考下

提到PHP開發(fā)web,自然離不開開發(fā)框架,開發(fā)框架為我們提供了靈活的開發(fā)方式,MVC層分離,業(yè)務(wù)解耦等。。。

第一篇先來簡單點(diǎn)的,說說MVC框架的路由功能。。。

一般的單入口框架路由都是這樣的結(jié)構(gòu):

domain/index.php/classname/functionname/var1/var2

這里的index.php 就被稱為入口文件。。。對于服務(wù)器而言,你這里訪問的就只有index.php 后面調(diào)用的controller 和里面的方法,甚至傳值都是在框架內(nèi)部基于PHP層面實(shí)現(xiàn)的。

Talk is cheap, show you the code !!

首先,先建立好下面的文件結(jié)構(gòu)

我們來動手試試,怎么才能訪問到controllers里面的文件。。。

在index.php里面輸入以下內(nèi)容

print_r($_SERVER);

然后訪問 以下地址試試。

yourdomain/index.php/class/function/var1

這里作者我是用本地環(huán)境的,我訪問的地址是localhost/MVC/index.php/class/function/var1

我貼出最重要的2個變量

[REQUEST_URI] => /MVC/index.php/class/function/var1
[SCRIPT_NAME] => /MVC/index.php

其實(shí)路由最基本的原理就在這里:

通過這2個變量來提取url地址里的class 和 function,參數(shù)等,然后把class include進(jìn)來,通過PHP的回調(diào)函數(shù)call_user_func_array 調(diào)用對應(yīng)的function和傳遞相應(yīng)的參數(shù)。

接下來上代碼,讀代碼應(yīng)該比我寫的易懂。哈哈~~

index.php 的內(nèi)容如下

<?php 
# 定義application路徑 
define(‘APPPATH', trim(__DIR__,'/')); 
# 獲得請求地址 
$root = $_SERVER['SCRIPT_NAME']; 
$request = $_SERVER['REQUEST_URI']; 
$URI = array(); 
# 獲得index.php 后面的地址 
$url = trim(str_replace($root, ”, $request), ‘/'); 
# 如果為空,則是訪問根地址 
if (empty($url)) 
{ 
# 默認(rèn)控制器和默認(rèn)方法 
$class = ‘index'; 
$func = ‘welcome'; 
} 
else 
{ 
$URI = explode(‘/', $url); 
# 如果function為空 則默認(rèn)訪問index 
if (count($URI) < 2) 
{ 
$class = $URI[0]; 
$func = ‘index'; 
} 
else 
{ 
$class = $URI[0]; 
$func = $URI[1]; 
} 
} 
# 把class加載進(jìn)來 
include(APPPATH . ‘/' . ‘a(chǎn)pplication/controllers/' . $class . ‘.php'); 
#實(shí)例化 
$obj = new ucfirst($class); 
call_user_func_array( 
# 調(diào)用內(nèi)部function 
array($obj,$func), 
# 傳遞參數(shù) 
array_slice($URI, 2) 
); 

在application/controllers 里面添加下面2個文件

index.php 用于作為默認(rèn)控制器

<?php 
class Index 
{ 
function welcome() 
{ 
echo ‘I am default controller'; 
} 
} 
?> 
hello.php
<?php 
class Hello 
{ 
public function index() 
{ 
echo ‘hello world'; 
} 
public function name($name) 
{ 
echo ‘hello ‘ . $name; 
} 
} 
?>

測試一下看看,能不能訪問了。根據(jù)上面的路由結(jié)構(gòu)。我們來試試

這個訪問正常,正確調(diào)用了hello這個class內(nèi)部的name方法,然后把參數(shù)barbery傳遞過去了。。。

再試試不輸入function name,看看能不能默認(rèn)調(diào)用index。。

答案也是可以的。。。

最后一個,訪問root地址看看

也正確的映射到了默認(rèn)控制器上。。。

ok,一個簡單的MVC路由功能就完成了。。。

相關(guān)文章

最新評論