一個php框架的簡單實現,僅實現簡單路由層

藏色散人
發布: 2023-04-09 17:28:02
轉載
3802 人瀏覽過

推薦:《PHP影片教學

首先看一下現有的檔案目錄

DOCUMENT_ROOR 為/home/www目錄

然後看一下入口檔案的內容

<?php
	$controll_action = $_GET[&#39;_ca_&#39;];
	$params  = explode(&#39;/&#39;,$controll_action);
	$params_count = count($params);

	$otherParams = $params;
	if($params_count>1) {
		$controller = $params[0];
		$action  = $params[1];
		unset($params[0]);
		unset($params[1]);
	}else if($params_count==1) {
		$controller = $params[0];
		$action = &#39;index&#39;;
		unset($params[0]);
	}

	$filename = strtolower($controller).&#39;.php&#39;;
	$controller_path = $_SERVER[&#39;DOCUMENT_ROOT&#39;].&#39;/application/controllers/&#39;;

	if(!file_exists($controller_path.$filename)) {
		throw new Exception(&#39;controller &#39;.$filename.&#39; is not exists!&#39;);
		return;
	}
	include($controller_path.$filename);

	$classname = ucfirst($controller);
	if(!class_exists($classname)) {
		throw new Excpetion(&#39;class &#39;.$classname.&#39; is not exists!&#39;);
	}
	$reflecObj = new ReflectionClass($classname);
	if(!$reflecObj->hasMethod($action)){
		throw new Exception(&#39;method &#39;.$action.&#39; is not exists!&#39;);
	}

	$currentObj = new $classname();
	echo "classname=$classname,action=$action,params=".json_encode($params)."<br/>";
	call_user_func_array([$currentObj,$action],$params);
	return;
?>
登入後複製

然後建立一個簡單的控制器user.php,放到applicaiton/controllers/目錄下,具體內容如下:

<?php
class User {
    
    function __construct(){
        
    }
    public function index($name=&#39;&#39;)
    {
    	echo &#39;hello,&#39;.$name.&#39;,lucky,you are arrive here!&#39;;
    }
}
登入後複製

最後測試一個正確的控制器跳轉和錯誤的控制器跳轉

首先測試正確的流程:http://192.168.1.99/user /index/xiaoming

輸出內容:

classname=User,action=index,params={"2":"xiaoming"}
 hello,xiaoming,lucky,you are arrive here!
登入後複製

再測試一下不存在的控制器,http://192.168.1.99/account/index/xiaoming

Fatal error: Uncaught exception &#39;Exception&#39; with message &#39;controller acount.php is not exists!&#39; in /home/www/webroot/index.php:25Stack trace:#0 {main} thrown in 
/home/www/webroot/index.php on line 25
登入後複製

以上是一個php框架的簡單實現,僅實現簡單路由層的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
php
來源:csdn.net
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!