ホームページ  >  記事  >  バックエンド開発  >  php フレームワークの単純な実装。単純なルーティング層のみを実装します。

php フレームワークの単純な実装。単純なルーティング層のみを実装します。

藏色散人
藏色散人転載
2020-12-31 14:48:503765ブラウズ

推奨: 「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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はcsdn.netで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。