前段时间写了个关于手机应用的api,一直是用的query_string这种地址,而且还是根据一个act参数来区分所有的动作,这种让开发人员看起来比较费眼。本来想改写为“?c=controller&m=method&type=3&id=1” 这种形式,利用m参数来载入文件并进行实例化,后来看了sina weibo api 是对地址进行了路由。也决定跟风对地址路由。本来CI框架自己自带路由效果,但是因为考虑是写api,想写的比较纯粹一点。
支持默认控制器(index)和方法(index):
index.php<BR>index.php/controller<BR>index.php/controller/method<BR>index.p<strong>*本文来源gaodai#ma#com搞@代~码^网+</strong><strong>搞代gaodaima码</strong>hp/controller/method/prarme1/value1<BR>index.php/controller/method/param1/value1/param2/value2.....<BR>
具体类如下:
<?phpdefine('MODULE_DIR', './classes/');<BR>$APP_PATH= str_replace($_SERVER['DOCUMENT_ROOT'], '', __FILE__); <BR>$SE_STRING=str_replace($APP_PATH, '', $_SERVER['REQUEST_URI']); //计算出index.php后面的字段 index.php/controller/methon/id/3<BR>$SE_STRING=trim($SE_STRING,'/');<BR>//echo $SE_STRING.'<br>';<BR>//这里需要对$SE_STRING进行过滤处理。<BR>$ary_url=array(<BR> 'controller'=>'index',<BR> 'method'=>'index',<BR> 'pramers'=>array()<BR> );<BR>//var_dump($ary_url);<BR>$ary_se=explode('/', $SE_STRING);<BR>$se_count=count($ary_se);</P><P>//路由控制<BR>if($se_count==1 and $ary_se[0]!='' ){<BR> $ary_url['controller']=$ary_se[0];</P><P>}else if($se_count>1){//计算后面的参数,key-value<BR> $ary_url['controller']=$ary_se[0];<BR> $ary_url['method']=$ary_se[1];<BR> if($se_count>2 and $se_count%2!=0){ //没有形成key-value形式<BR> die('参数错误');<BR> }else{<BR> for($i=2;$i < $se_count;$i=$i+2){<BR> $ary_kv_hash=array(strtolower($ary_se[$i])=>$ary_se[$i+1]);<BR> $ary_url[pramers]=array_merge($ary_url[pramers],$ary_kv_hash);<BR> }<BR> }<BR>}</P><P><BR>$module_name=$ary_url['controller'];<BR>$module_file=MODULE_DIR.$module_name.'.class.php';<BR>//echo $module_file;<BR>$method_name=$ary_url['method'];<BR>if(file_exists($module_file)){<BR> include($module_file);<BR> $obj_module=new $module_name(); //实例化模块m</P><P> if(!method_exists($obj_module, $method_name)){<BR> die('方法不存在');<BR> }else{<BR> if(is_callable(array($obj_module, $method_name))){ //该方法是否能被调用<BR> //var_dump($ary_url[pramers]);<BR> $get_return=$obj_module->$method_name($ary_url[pramers]); //执行a方法,并把key-value参数的数组传过去<BR> if(!is_null($get_return)){ //返回值不为空<BR> var_dump($get_return);<BR> }<br><br> }else{<BR> die('该方法不能被调用');<BR> }<br><br> }<BR>}<BR>else<BR>{<BR> die('模块文件不存在');<BR>}<BR>?><BR>