一个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



ok,就到这里吧,祝大家春节快乐,幸福美满。




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值