温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

实现一个简单php框架的示例

发布时间:2021-01-05 11:26:36 来源:亿速云 阅读:205 作者:小新 栏目:编程语言

小编给大家分享一下实现一个简单php框架的示例,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

首先看一下现有的文件目录

实现一个简单php框架的示例

DOCUMENT_ROOR 为 /home/www目录

然后看一下入口文件的内容

<?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;
?>

然后创建一个简单的控制器 user.php,放到applicaiton/controllers/目录下,具体内容如下:

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

最后测试一个正确的控制器跳转和错误的控制器跳转

首先测试一下正确的流程: 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 '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

看完了这篇文章,相信你对“实现一个简单php框架的示例”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php
AI