溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

實現(xiàn)一個簡單php框架的示例

發(fā)布時間:2021-01-05 11:26:36 來源:億速云 閱讀:211 作者:小新 欄目:編程語言

小編給大家分享一下實現(xiàn)一個簡單php框架的示例,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

首先看一下現(xiàn)有的文件目錄

實現(xiàn)一個簡單php框架的示例

DOCUMENT_ROOR 為 /home/www目錄

然后看一下入口文件的內(nèi)容

<?php
	$controll_action = $_GET['_ca_'];
	$params  = explode('/',$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 = 'index';
		unset($params[0]);
	}

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

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

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

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

然后創(chuàng)建一個簡單的控制器 user.php,放到applicaiton/controllers/目錄下,具體內(nèi)容如下:

<?php
class User {
    
    function __construct(){
        
    }
    public function index($name='')
    {
    	echo 'hello,'.$name.',lucky,you are arrive here!';
    }
}

最后測試一個正確的控制器跳轉(zhuǎn)和錯誤的控制器跳轉(zhuǎn)

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

輸出內(nèi)容:

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 'Exception' with message 'controller acount.php is not exists!' in /home/www/webroot/index.php:25Stack trace:#0 {main} thrown in 
/home/www/webroot/index.php on line 25

看完了這篇文章,相信你對“實現(xiàn)一個簡單php框架的示例”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI