学习如何写PHP MVC框架(1) -- 路由
說到PHP開發(fā)web,自然離不開開發(fā)框架,開發(fā)框架為我們提供了靈活的開發(fā)方式,MVC層分離,業(yè)務(wù)解耦等。。。
第一篇先來簡單點的,說說MVC框架的路由功能。。。
一般的單入口框架路由都是這樣的結(jié)構(gòu):
domain/index.php/classname/functionname/var1/var2
這里的index.php 就被稱為入口文件。。。對于服務(wù)器而言,你這里訪問的就只有index.php 后面調(diào)用的controller 和里面的方法,甚至傳值都是在框架內(nèi)部基于PHP層面實現(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
其實路由最基本的原理就在這里:
通過這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)容如下
1 <?php 2 3 # 定義application路徑 4 define('APPPATH', trim(__DIR__,'/')); 5 6 # 獲得請求地址 7 $root = $_SERVER['SCRIPT_NAME']; 8 $request = $_SERVER['REQUEST_URI']; 9 10 $URI = array(); 11 12 # 獲得index.php 后面的地址 13 $url = trim(str_replace($root, '', $request), '/'); 14 15 # 如果為空,則是訪問根地址 16 if (empty($url)) 17 { 18 # 默認(rèn)控制器和默認(rèn)方法 19 $class = 'index'; 20 $func = 'welcome'; 21 } 22 else 23 { 24 $URI = explode('/', $url); 25 26 # 如果function為空 則默認(rèn)訪問index 27 if (count($URI) < 2) 28 { 29 $class = $URI[0]; 30 $func = 'index'; 31 } 32 else 33 { 34 $class = $URI[0]; 35 $func = $URI[1]; 36 } 37 } 38 39 40 # 把class加載進(jìn)來 41 include(APPPATH . '/' . 'application/controllers/' . $class . '.php'); 42 43 #實例化 44 $obj = new ucfirst($class); 45 46 call_user_func_array( 47 # 調(diào)用內(nèi)部function 48 array($obj,$func), 49 # 傳遞參數(shù) 50 array_slice($URI, 2) 51 );在application/controllers 里面添加下面2個文件
index.php?? 用于作為默認(rèn)控制器
1 <?php 2 3 class Index 4 { 5 6 function welcome() 7 { 8 echo 'I am default controller'; 9 } 10 11 } 12 13 14 ?>hello.php
1 <?php 2 class Hello 3 { 4 public function index() 5 { 6 echo 'hello world'; 7 } 8 9 public function name($name) 10 { 11 echo 'hello ' . $name; 12 } 13 } 14 15 ?>測試一下看看,能不能訪問了。根據(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路由功能就完成了。。。
轉(zhuǎn)載于:https://www.cnblogs.com/CHEUNGKAMING/p/4080936.html
總結(jié)
以上是生活随笔為你收集整理的学习如何写PHP MVC框架(1) -- 路由的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 更改UISearchBar button
- 下一篇: 一、spring mvc简介