Skip to content

Instantly share code, notes, and snippets.

@forecho
Created November 7, 2013 05:36
Show Gist options
  • Save forecho/7349546 to your computer and use it in GitHub Desktop.
Save forecho/7349546 to your computer and use it in GitHub Desktop.
<?php
/*
Author: icanc <i@icanc.net>
*/
function R( $Request='/',array $Router ){
$Response = array();
if( !is_string($Request) )
return $Response;
foreach ( $Router[$_SERVER['REQUEST_METHOD']] as $key => $fn ) {
$parameter = null;
if( strpos( $key , '/' ) !== 0 ){
$parameter = array();
}
else{
if( preg_match_all('#^'.$key.'$#mi', $Request ,$para ,PREG_SET_ORDER,0) ){
$parameter = array();
array_shift($para[0]);
foreach ($para[0] as $v)
$parameter[]=$v;
}
}
if( $parameter !== null ){
if( is_string($fn) && strpos($fn,'->') ){
$fn=explode('->',$fn);
$c = new $fn[0];
$fn=array($c,$fn[1]);
}
$result = call_user_func_array($fn, $parameter );
if( null === $result )
break;
$Response[] = $result;
}
}
return $Response;
}
$Router=array(
'GET'=>array(
'/'=>function(){
return 'hello world!';
},
'/([a-z]+)'=>function($name){
return 'hello,'.$name;
},
// 小括号里的参数会依次作为后面函数的参数,类方法也一样
'/([a-z]+)/([a-z]+)'=>function($argv1,$argv2){
return 'argv1:'.$argv1.' argv2:'.$argv2;
},
'/phpinfo'=>'phpinfo',
'/md5/(.*)'=>'md5',
'/login'=>function(){
//require 'login.html';
/*
如果函数返回值为 null,则会跳出路由遍历,
这里可以 return null;
或者暴力一点: die() or exit();
处理登录验证一般是 POST 提交,所以相关路由放在下面的 POST 里,当然,也要放在 POST 里 RequestLogin 之前
*/
},
//如果索引首字符不是 / ,则后面的函数一定会执行, 可以当 hook 用
// 这里会判断用户是否登录,如果没有登陆则跳到 /login。/login 一定要在 RequestLogin 之前,不然死循环
'RequestLogin'=>function(){
if( 1 /* isLogin*/){
return true;
}
else{
header('Location:/login');
exit();
}
},
//调用类静态方法
'/test1'=>'Class1::Method',
//调用类动态方法
'/test2'=>'Class1->Method2',
// something secret
),
'POST'=>array(),
'PUT'=>array(),
'DELETE'=>array()
);
var_dump( R( $_SERVER['REQUEST_URI'] ,$Router ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment